Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:org.jenkinsci.plugins.testrail.TestRailClient.java

public Case[] getCases(int projectId, int suiteId) throws IOException, ElementNotFoundException {
    // "/#{project_id}&suite_id=#{suite_id}#{section_string}"
    String body = httpGet("index.php?/api/v2/get_cases/" + projectId + "&suite_id=" + suiteId).getBody();
    JSONArray json = new JSONArray(body);

    Case[] cases = new Case[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        cases[i] = createCaseFromJson(o);
    }/*from   w  ww. j  av  a2s.  com*/

    return cases;
}

From source file:org.jenkinsci.plugins.testrail.TestRailClient.java

public Section[] getSections(int projectId, int suiteId) throws IOException, ElementNotFoundException {
    String body = httpGet("index.php?/api/v2/get_sections/" + projectId + "&suite_id=" + suiteId).getBody();
    JSONArray json = new JSONArray(body);

    Section[] sects = new Section[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        sects[i] = createSectionFromJSON(o);
    }/*from   w  w w.j a v  a 2  s .  c  om*/

    return sects;
}

From source file:org.jenkinsci.plugins.testrail.TestRailClient.java

public Milestone[] getMilestones(int projectId) throws IOException, ElementNotFoundException {
    String body = httpGet("index.php?/api/v2/get_milestones/" + projectId).getBody();
    JSONArray json;
    try {/*from   ww  w  .jav  a 2 s  . c  o m*/
        json = new JSONArray(body);
    } catch (JSONException e) {
        return new Milestone[0];
    }
    Milestone[] suites = new Milestone[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        Milestone s = new Milestone();
        s.setName(o.getString("name"));
        s.setId(String.valueOf(o.getInt("id")));
        suites[i] = s;
    }
    return suites;
}

From source file:com.fsa.en.dron.activity.MainActivity.java

private void fetchImages() {

    pDialog.setMessage("Levantando vuelo...");
    pDialog.setCanceledOnTouchOutside(false);
    pDialog.show();//w  w w  .  ja v a 2  s.c  om

    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, endpoint, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                    JSONArray array = null;

                    try {
                        JSONObject user = response.getJSONObject("photos");
                        array = user.getJSONArray("photo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    images.clear();
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            JSONObject object = array.getJSONObject(i);
                            Image image = new Image();

                            image.setSmall("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setMedium("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setLarge("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setUrl("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setId(object.getString("id"));
                            Log.i("uuu", "" + "https://farm2.staticflickr.com/" + object.getString("server")
                                    + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            images.add(image);

                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Error: " + error.getMessage());
                    pDialog.hide();
                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);
}

From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {/*from  w w  w .  j  a  va  2  s  . c om*/
        JSONObject obj = new JSONObject(input);
        if ("OK".equals(obj.getString("status"))) {
            JSONArray results = obj.getJSONArray("results");
            boolean ambiguous = results.length() > 1;
            int limit = results.length();
            if (this.getLimit() > 0)
                limit = Math.min(this.getLimit(), limit);
            for (int i = 0; i < limit; i++) {
                JSONObject result = results.getJSONObject(i);
                GeocodedLocation loc = new GeocodedLocation();
                loc.setAmbiguous(ambiguous);
                loc.setOriginalAddress(address);
                loc.setGeocodedAddress(result.getString("formatted_address"));
                JSONArray components = result.getJSONArray("address_components");
                for (int j = 0; j < components.length(); j++) {
                    JSONObject component = components.getJSONObject(j);
                    String value = component.getString("short_name");
                    JSONArray types = component.getJSONArray("types");
                    for (int k = 0; k < types.length(); k++) {
                        String type = types.getString(k);
                        if ("street_number".equals(type))
                            loc.setStreetNumber(value);
                        else if ("route".equals(type))
                            loc.setRoute(value);
                        else if ("locality".equals(type))
                            loc.setLocality(value);
                        else if ("administrative_area_level_1".equals(type))
                            loc.setAdministrativeAreaLevel1(value);
                        else if ("administrative_area_level_2".equals(type))
                            loc.setAdministrativeAreaLevel2(value);
                        else if ("country".equals(type))
                            loc.setCountry(value);
                        else if ("postal_code".equals(type))
                            loc.setPostalCode(value);
                    }
                }
                JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
                loc.setLat(location.getDouble("lat"));
                loc.setLon(location.getDouble("lng"));
                loc.setType(getLocationType(result));
                locations.add(loc);
            }
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}

From source file:info.aamulumi.tomate.APIConnection.java

/**
 * Send a GET request and create a list with returned JSON datas.
 * The JSONObject returned by server must have :
 * - success : int - 1 if request is successful
 * - data : JSONArray - contains datas which will be parsed
 *
 * @param url            - url to access
 * @param parseMethod    - name of the method used to parse an object in data
 * @param urlParameters  - parameters send in URL
 * @param bodyParameters - parameters send in body (encoded)
 * @return the list of parsed elements/*from www.  j  av  a  2 s .  co m*/
 */
private static <T> ArrayList<T> getItems(String url, String parseMethod, HashMap<String, String> urlParameters,
        HashMap<String, String> bodyParameters) {
    ArrayList<T> list = new ArrayList<>();

    // Get parseMethod
    Class<?>[] cArg = new Class[1];
    cArg[0] = JSONObject.class;

    Method parse;
    try {
        parse = APIConnection.class.getMethod(parseMethod, cArg);
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
        return null;
    }

    // Do the request
    JSONObject json = makeHttpRequest(url, GET, urlParameters, bodyParameters);

    if (json == null)
        return null;
    try {
        int success = json.getInt("success");
        // Parse if successful
        if (success == 1) {
            JSONArray data = json.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                @SuppressWarnings("unchecked")
                T tmp = (T) parse.invoke(APIConnection.class, data.getJSONObject(i));
                list.add(tmp);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return list;
}

From source file:com.liferay.mobile.android.v7.dlfileversion.DLFileVersionService.java

public JSONObject getFileVersion(long fileVersionId) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from  w w  w  .  j ava 2 s  .c om*/
        JSONObject _params = new JSONObject();

        _params.put("fileVersionId", fileVersionId);

        _command.put("/dlfileversion/get-file-version", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.liferay.mobile.android.v7.dlfileversion.DLFileVersionService.java

public JSONObject getLatestFileVersion(long fileEntryId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from  w ww.  jav  a  2  s.c  om
        JSONObject _params = new JSONObject();

        _params.put("fileEntryId", fileEntryId);

        _command.put("/dlfileversion/get-latest-file-version", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.liferay.mobile.android.v7.dlfileversion.DLFileVersionService.java

public JSONObject getLatestFileVersion(long fileEntryId, boolean excludeWorkingCopy) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from   ww  w . j  a va  2  s. c  o m*/
        JSONObject _params = new JSONObject();

        _params.put("fileEntryId", fileEntryId);
        _params.put("excludeWorkingCopy", excludeWorkingCopy);

        _command.put("/dlfileversion/get-latest-file-version", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.chinaftw.music.model.MusicProvider.java

private synchronized void retrieveMedia() {
    try {//  w  ww . j  a v a  2 s .c om
        if (mCurrentState == State.NON_INITIALIZED) {
            mCurrentState = State.INITIALIZING;

            JSONObject jsonObj = MusicAPI.getPlaylistDetails("60198");
            if (jsonObj == null) {
                return;
            }
            JSONArray tracks = jsonObj.getJSONArray(JSON_TRACKS);
            if (tracks != null) {
                for (int j = 0; j < 20; j++) {
                    MediaMetadata item = buildFromJSON(tracks.getJSONObject(j));
                    String musicId = item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
                    mMusicListById.put(musicId, new MutableMediaMetadata(musicId, item));
                }
                buildListsByGenre();
            }
            mCurrentState = State.INITIALIZED;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (mCurrentState != State.INITIALIZED) {
            // Something bad happened, so we reset state to NON_INITIALIZED to allow
            // retries (eg if the network connection is temporary unavailable)
            mCurrentState = State.NON_INITIALIZED;
        }
    }
}