List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:com.github.koraktor.steamcondenser.community.SteamId.java
/** * Fetches the friends of this user// w w w . ja v a 2s. c o m * <p> * This creates a new <code>SteamId</code> instance for each of the friends * without fetching their data. * * @see #getFriends * @see SteamId#SteamId * @throws SteamCondenserException if an error occurs while parsing the * data */ private void fetchFriends() throws SteamCondenserException { try { Map<String, Object> params = new HashMap<String, Object>(); params.put("relationship", "friend"); params.put("steamid", this.steamId64); JSONObject jsonData = new JSONObject(WebApi.getJSON("ISteamUser", "GetFriendList", 1, params)); JSONArray friendsData = jsonData.getJSONObject("friendslist").getJSONArray("friends"); this.friends = new ArrayList<SteamId>(); for (int i = 0; i < friendsData.length(); i++) { JSONObject friend = friendsData.getJSONObject(i); this.friends.add(new SteamId(friend.getLong("steamid"), false)); } } catch (JSONException e) { throw new WebApiException("Could not parse JSON data.", e); } }
From source file:ezy.boost.update.UpdateInfo.java
public static UpdateInfo parse(String s) throws JSONException { JSONObject o = new JSONObject(s); return parse(o.has("data") ? o.getJSONObject("data") : o); }
From source file:com.fsa.en.dron.activity.MainActivity.java
private void fetchImages() { pDialog.setMessage("Levantando vuelo..."); pDialog.setCanceledOnTouchOutside(false); pDialog.show();//from w w w . j ava2s . c o m 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 {// ww w .j a v a2 s . c o m 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 HTTP request and parse the returned element. * The JSONObject returned by server must have : * - success : int - 1 if request is successful * - data : JSONObject - element which will be parsed * * @param url - url to access * @param method - HTTP method (GET, PUT, ...) * @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 w w w. j a v a 2 s . c o m*/ */ @SuppressWarnings("unchecked") private static <T> T doHTTPRequestAndParse(String url, String method, String parseMethod, HashMap<String, String> urlParameters, HashMap<String, String> bodyParameters) { // 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, method, urlParameters, bodyParameters); if (json == null) return null; try { int success = json.getInt("success"); // Parse if successful if (success == 1) { return (T) parse.invoke(APIConnection.class, json.getJSONObject("data")); } } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:com.chinaftw.music.model.MusicProvider.java
private MediaMetadata buildFromJSON(JSONObject json) throws JSONException { String id = String.valueOf(json.getInt(JSON_SONG_ID)); String title = json.getString(JSON_TITLE); String album = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_NAME); String albumId = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_ID); String artist = json.getJSONArray(JSON_ARTIST).getJSONObject(0).getString(JSON_ARTIST_NAME); String artistId = json.getJSONObject(JSON_ALBUM).getString(JSON_ARTIST_ID); String imageId = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_IMAGE_ID); int duration = json.getInt(JSON_DURATION); // ms LogHelper.d(TAG, "Found music track: ", json); String source = MusicAPI.getSongUrl(id); String imageUri = MusicAPI.getPictureUrl(imageId); // Since we don't have a unique ID in the server, we fake one using the hashcode of // the music source. In a real world app, this could come from the server. // Adding the music source to the MediaMetadata (and consequently using it in the // mediaSession.setMetadata) is not a good idea for a real world music app, because // the session metadata can be accessed by notification listeners. This is done in this // sample for convenience only. return new MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_MEDIA_ID, id) .putString(CUSTOM_METADATA_TRACK_SOURCE, source).putString(MediaMetadata.METADATA_KEY_ALBUM, album) .putString(MediaMetadata.METADATA_KEY_ARTIST, artist) .putLong(MediaMetadata.METADATA_KEY_DURATION, duration) .putString(MediaMetadata.METADATA_KEY_GENRE, "BILLBOARD") //TODO .putString(MediaMetadata.METADATA_KEY_TITLE, title) .putString(MediaMetadata.METADATA_KEY_ART_URI, imageUri) .putString(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, imageUri) .putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, imageUri).build(); }
From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java
/** * Positive test case for addComment method with mandatory parameters. *///ww w. j a v a 2 s . c o m @Test(priority = 1, groups = { "wso2.esb" }, description = "flickr {addComment} integration test with mandatory parameters") public void testFlickrAddCommentWithMandatoryParameters() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "flickr_addComment.txt"; String methodName = "flickr_addComment"; String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); rawString = rawString.replace("dummyvalue", flickrConnectorProperties.getProperty("photoId")); final String jsonString = addCredentials(rawString); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); try { JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST", getProxyServiceURL(methodName), jsonString); String httpMethod = "GET"; String parameters = "format=json&nojsoncallback=1&method=flickr.photos.comments.getList&api_key=" + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id=" + flickrConnectorProperties.getProperty("photoId"); JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters, flickrConnectorProperties); String commentIdConnector = responseConnector.getJSONObject("comment").getString("id"); addCommentMethodCommentId = commentIdConnector; //keeping the comment id to be used in deleteComment method. Assert.assertTrue(responseDirect.toString().contains(commentIdConnector)); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java
/** * Positive test case for addTags method with mandatory parameters. *///from w w w. j a va 2s. com @Test(priority = 1, groups = { "wso2.esb" }, description = "flickr {addTags} integration test with mandatory parameters") public void testFlickrAddTagsWithMandatoryParameters() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "flickr_addTags.txt"; String methodName = "flickr_addTags"; String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); rawString = rawString.replace("dummyvalue", flickrConnectorProperties.getProperty("photoId")); rawString = rawString.replace("tagName", flickrConnectorProperties.getProperty("tagName") + System.currentTimeMillis()); final String jsonString = addCredentials(rawString); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); try { JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST", getProxyServiceURL(methodName), jsonString); String httpMethod = "GET"; String parameters = "format=json&nojsoncallback=1&method=flickr.photos.getInfo&api_key=" + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id=" + flickrConnectorProperties.getProperty("photoId"); JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters, flickrConnectorProperties); addTagMethodTagId = ((JSONObject) responseConnector.getJSONObject("tags").getJSONArray("tag").get(0)) .getString("full_tag_id"); Assert.assertTrue(responseDirect.toString().contains(addTagMethodTagId)); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:com.nextgis.maplib.datasource.ngw.LayerWithStyles.java
public void fillStyles() { mStyles = new ArrayList<>(); try {/*from w ww. jav a 2s.c om*/ String sURL = mConnection.getURL() + "/resource/" + mRemoteId + "/child/"; HttpGet get = new HttpGet(sURL); get.setHeader("Cookie", mConnection.getCookie()); get.setHeader("Accept", "*/*"); HttpResponse response = mConnection.getHttpClient().execute(get); HttpEntity entity = response.getEntity(); JSONArray children = new JSONArray(EntityUtils.toString(entity)); for (int i = 0; i < children.length(); i++) { //Only store style id //To get more style properties need to create style class extended from Resource //Style extends Resource //mStyles.add(new Style(styleObject, mConnection); JSONObject styleObject = children.getJSONObject(i); JSONObject JSONResource = styleObject.getJSONObject("resource"); long remoteId = JSONResource.getLong("id"); mStyles.add(remoteId); } } catch (IOException | JSONException e) { e.printStackTrace(); } }
From source file:com.kevinquan.android.utils.JSONUtils.java
/** * Retrieve the JSON object stored at the provided key from the provided JSON object * @param obj The JSON object to retrieve from * @param key The key to retrieve//from w w w . j a v a2 s .co m * @return the JSON object stored in the key, or null if the key doesn't exist */ public static JSONObject safeGetJSONObject(JSONObject obj, String key) { if (obj == null || TextUtils.isEmpty(key)) return null; if (obj.has(key)) { try { return obj.getJSONObject(key); } catch (JSONException e) { Log.w(TAG, "Could not get JSON object from key " + key, e); } } return null; }