org.json.JSONObject类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(13.6k)|赞(0)|评价(0)|浏览(362)

本文整理了Java中org.json.JSONObject类的一些代码示例,展示了JSONObject类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JSONObject类的具体详情如下:
包路径:org.json.JSONObject
类名称:JSONObject

JSONObject介绍

[英]A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObject, JSONArray, Strings, Booleans, Integers, Longs, Doubles or #NULL. Values may not be null, Double#isNaN(), Double#isInfinite(), or of any type not listed here.

This class can coerce values to another type when requested.

This class can look up both mandatory and optional values:

  • Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value cannot be coerced to the requested type.
  • Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the value cannot be coerced to the requested type.

Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value JSONObject#NULL. In particular, calling put(name, null) removes the named entry from the object but put(name, JSONObject.NULL) stores an entry whose value is JSONObject.NULL.

Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overrideable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.
[中]可修改的名称/值映射集。名称是唯一的非空字符串。值可以是JSONObject、JSONArray、字符串、布尔、整数、长、双精度或#NULL的任意组合。值不能为null、Double#isNaN()、Double#isInfinite()或此处未列出的任何类型。
此类可以在请求时将值强制为其他类型。
*当请求的类型是布尔类型时,将使用不区分大小写的比较“true”和“false”强制字符串。
*当请求的类型为double时,将使用Number#doubleValue()强制其他数字类型。可以使用Double#valueOf(String)强制的字符串将被删除。
*当请求的类型为int时,将使用Number#intValue()强制其他数字类型。可以使用Double#valueOf(String)强制的字符串将为,然后强制转换为int。

代码示例

canonical example by Tabnine

public String creatingJsonString() {
  JSONArray pets = new JSONArray();
  pets.put("cat");
  pets.put("dog");
  JSONObject person = new JSONObject();
  person.put("name", "John Brown");
  person.put("age", 35);
  person.put("pets", pets);
  return person.toString(2);
}

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);
  }
}

代码示例来源:origin: stackoverflow.com

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);

代码示例来源:origin: stackoverflow.com

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");
}

代码示例来源:origin: google/physical-web

/**
 * 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());
}

代码示例来源:origin: bumptech/glide

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");
}

代码示例来源:origin: stackoverflow.com

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");
  ......
}

代码示例来源:origin: stackoverflow.com

for (int i = 0; i < recs.length(); ++i) {
  JSONObject rec = recs.getJSONObject(i);
  int id = rec.getInt("id");
  String loc = rec.getString("loc");
  // ...
}

代码示例来源:origin: stackoverflow.com

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());

代码示例来源:origin: stackoverflow.com

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());

代码示例来源:origin: stackoverflow.com

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");

代码示例来源:origin: loklak/loklak_server

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();
  }
}

代码示例来源:origin: stackoverflow.com

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;

代码示例来源:origin: stackoverflow.com

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());

代码示例来源:origin: stackoverflow.com

// 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();

代码示例来源:origin: stackoverflow.com

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);

代码示例来源:origin: stackoverflow.com

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;
 }

代码示例来源:origin: stackoverflow.com

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();      
 }

代码示例来源:origin: stackoverflow.com

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;

代码示例来源:origin: stackoverflow.com

// 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);

相关文章

微信公众号

最新文章

更多

JSONObject类方法