canonical example by Tabnine
canonical example by Tabnine
public void accessingJson(JSONObject json) { Object invalid = json.get("invalid"); // throws JSONException - "invalid" entry doesn't exists String name = json.getString("name"); // name = "John Brown" int number = json.getInt("name"); // throws JSONException - "name" entry isn't int int age = json.optInt("age", 42); // using default value instead of throwing exception JSONArray pets = json.getJSONArray("pets"); for (int i = 0; i < pets.length(); i++) { String pet = pets.getString(i); } }
JSONObject jo = new JSONObject(); jo.put("firstName", "John"); jo.put("lastName", "Doe"); JSONArray ja = new JSONArray(); ja.put(jo); JSONObject mainObj = new JSONObject(); mainObj.put("employees", ja);
int id; String name; JSONArray array = new JSONArray(string_of_json_array); for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); id = row.getInt("id"); name = row.getString("name"); }
/** * Construct a UrlDevice. * @param id The id of the device. * @param url The URL broadcasted by the device. * @param extraData Extra data to associate with this UrlDevice. */ private UrlDevice(String id, String url, JSONObject extraData) { mId = id; mUrl = url; mExtraData = extraData == null ? new JSONObject() : new JSONObject(extraData.toString()); }
public Photo(JSONObject jsonPhoto) throws JSONException { this.id = jsonPhoto.getString("id"); this.owner = jsonPhoto.getString("owner"); this.title = jsonPhoto.optString("title", ""); this.server = jsonPhoto.getString("server"); this.farm = jsonPhoto.getString("farm"); this.secret = jsonPhoto.getString("secret"); }
import org.json.*; JSONObject obj = new JSONObject(" .... "); String pageName = obj.getJSONObject("pageInfo").getString("pageName"); JSONArray arr = obj.getJSONArray("posts"); for (int i = 0; i < arr.length(); i++) { String post_id = arr.getJSONObject(i).getString("post_id"); ...... }
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); new JSONObject(responseStrBuilder.toString());
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token"); try nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET)); nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); org.apache.http.HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer buffer = new StringBuffer(); for (String line = reader.readLine(); line != null; line = reader.readLine()) JSONObject json = new JSONObject(buffer.toString()); String accessToken = json.getString("access_token");
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } }
throws ClientProtocolException, IOException, JSONException HttpClient httpClient = new DefaultHttpClient(); HttpHost httpHost = new HttpHost(host, port); HttpPost httpPost = new HttpPost(uri); httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8"); httpPost.setEntity(bodyEntity); HttpResponse response = httpClient.execute(httpHost, httpPost); HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream)); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) sb.append(line + "\n"); httpPost.abort(); return result != null ? new JSONObject(result) : null;
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpResponse httpResponse = httpClient.execute(httpGet); BufferedReader httpResponseReader = new BufferedReader( new InputStreamReader(httpResponseStream, "iso-8859-1"), 8); while ((line = httpResponseReader.readLine()) != null) { return new JSONObject(jsonString); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString());
// Create a new HTTP Client DefaultHttpClient defaultClient = new DefaultHttpClient(); // Setup the get request HttpGet httpGetRequest = new HttpGet("http://example.json"); // Execute the request in the client HttpResponse httpResponse = defaultClient.execute(httpGetRequest); // Grab the response BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); // Instantiate a JSON object from the request response JSONObject jsonObject = new JSONObject(json); // Save the JSONOvject ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl")); out.writeObject( jsonObject ); out.close();
JSONObject JOTemp = new JSONObject(queryAlbums); JSONArray JAPhotos = JOTemp.getJSONArray("data"); if (JOPhotos.has("link")) { if (JOPhotos.has("id")) { photos.setPhotoID(JOPhotos.getString("id")); } else { photos.setPhotoID(null); if (JOPhotos.has("name")) { photos.setPhotoName(JOPhotos.getString("name")); } else { photos.setPhotoName(null); if (JOPhotos.has("picture")) { photos.setPhotoPicture(JOPhotos .getString("picture")); } else { photos.setPhotoPicture(null); if (JOPhotos.has("source")) { photos.setPhotoSource(JOPhotos .getString("source")); } else { photos.setPhotoSource(null);
public static JSONObject getLocationInfo(String address) { StringBuilder stringBuilder = new StringBuilder(); try { address = address.replaceAll(" ","%20"); HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false"); HttpClient client = new DefaultHttpClient(); HttpResponse response; stringBuilder = new StringBuilder(); response = client.execute(httppost); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; }
protected void sendJson(final String email, final String pwd) { Thread t = new Thread() { public void run() { Looper.prepare(); //For Preparing Message Pool for the child Thread HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit HttpResponse response; JSONObject json = new JSONObject(); try { HttpPost post = new HttpPost(URL); json.put("email", email); json.put("password", pwd); StringEntity se = new StringEntity( json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); /*Checking response */ if(response!=null){ InputStream in = response.getEntity().getContent(); //Get the data in the entity } } catch(Exception e) { e.printStackTrace(); createDialog("Error", "Cannot Estabilish Connection"); } Looper.loop(); //Loop in the message queue } }; t.start(); }
boolean result = false; HttpClient hc = new DefaultHttpClient(); String message; HttpPost p = new HttpPost(url); JSONObject object = new JSONObject(); try { object.put("updates", updates); object.put("mobile", mobile); object.put("last_name", lastname); object.put("first_name", firstname); object.put("email", email); } catch (Exception ex) { } try { message = object.toString(); p.setEntity(new StringEntity(message, "UTF8")); p.setHeader("Content-type", "application/json"); HttpResponse resp = hc.execute(p); if (resp != null) { if (resp.getStatusLine().getStatusCode() == 204) result = true; } Log.d("Status line", "" + resp.getStatusLine().getStatusCode()); } catch (Exception e) { e.printStackTrace(); } return result;
// Build the JSON object to pass parameters JSONObject jsonObj = new JSONObject(); jsonObj.put("username", username); jsonObj.put("apikey", apikey); // Create the POST object and add the parameters HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8); entity.setContentType("application/json"); httpPost.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpPost);