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

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

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

JSONArray介绍

[英]A dense indexed sequence of values. Values may be any mix of JSONObject, other JSONArray, Strings, Booleans, Integers, Longs, Doubles, null or JSONObject#NULL. Values may not be Double#isNaN(), Double#isInfinite(), or of any type not listed here.

JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject. See that class' documentation for details.

Warning: this class represents null in two incompatible ways: the standard Java null reference, and the sentinel value JSONObject#NULL. In particular, get fails if the requested index holds the null reference, but succeeds if it holds 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 overridable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.
[中]密集的索引值序列。值可以是JSONObject、其他JSONArray、字符串、布尔值、整数、long值、double值、null值或JSONObject#null值的任意组合。值不能是Double#isNaN()、Double#isInfinite(),也不能是此处未列出的任何类型。
JSONArray与JSONObject具有相同的类型强制行为和可选/强制访问器。有关详细信息,请参阅该类的文档。
警告:此类以两种不兼容的方式表示null:标准Java null引用和sentinel值JSONObject#null。特别是,如果请求的索引包含null引用,get将失败,但如果它包含JSONObject,get将成功。无效的
此类的实例不是线程安全的。虽然这个类是非最终类,但它不是为继承而设计的,不应该被子类化。特别是,未指定可重写方法的自用。有关更多信息,请参见有效的Java项目17“设计和文档或继承或禁止”。

代码示例

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: bumptech/glide

List<Photo> parse(String response) throws JSONException {
  JSONObject searchResults =
    new JSONObject(response.substring(FLICKR_API_PREFIX_LENGTH, response.length() - 1));
  JSONArray photos = searchResults.getJSONObject("photos").getJSONArray("photo");
  List<Photo> results = new ArrayList<>(photos.length());
  for (int i = 0, size = photos.length(); i < size; i++) {
   results.add(new Photo(photos.getJSONObject(i)));
  }

  return results;
 }
}

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

public static JSONArray 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);
    JSONArray json = new JSONArray(jsonText);
    return json;
  } finally {
    is.close();
  }
}

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

try {
     JSONObject parent = new JSONObject();
     JSONObject jsonObject = new JSONObject();
     JSONArray jsonArray = new JSONArray();
     jsonArray.put("lv1");
     jsonArray.put("lv2");
     jsonObject.put("mk1", "mv1");
     jsonObject.put("mk2", jsonArray);
     parent.put("k2", jsonObject);
     Log.d("output", parent.toString(2));
   } catch (JSONException e) {
     e.printStackTrace();
   }

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

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
  JSONObject object = array.getJSONObject(n);
  // do some stuff....
}

代码示例来源:origin: zzz40500/GsonFormat

/**
 * Put a value in the JSONArray, where the value will be a JSONArray which
 * is produced from a Collection.
 *
 * @param value
 *            A Collection value.
 * @return this.
 */
public JSONArray put(Collection<Object> value) {
  this.put(new JSONArray(value));
  return this;
}

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

private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
    throws JSONException {
  JSONArray result = new JSONArray();
  for (int i = 0; i < arr1.length(); i++) {
    result.put(arr1.get(i));
  }
  for (int i = 0; i < arr2.length(); i++) {
    result.put(arr2.get(i));
  }
  return result;
}

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

String url = "http://maps.googleapis.com/maps/api/directions/json?origin=19.5217608,-99.2615823&destination=19.531224,-99.248262&sensor=false";

HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = null;
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
  sb.append(line + "\n");
}
is.close();
reader.close();
String result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<GeoPoint> pointToDraw = decodePoly(encodedString);

//Added line:
mapView.getOverlays().add(new RoutePathOverlay(pointToDraw));

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

HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://website.com/download.html");
 HttpResponse response = httpclient.execute(httppost);
 HttpEntity entity = response.getEntity();
 InputStream 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");
JSONArray jArray = new JSONArray(result);
 for(int i=0;i<jArray.length();i++){
     JSONObject json_data = jArray.getJSONObject(i);
     names.add("   " + json_data.getString("name"));
     age.add("   " + Integer.toString(json_data.getInt("age")));

代码示例来源:origin: avjinder/Minimal-Todo

public ArrayList<ToDoItem> loadFromFile() throws IOException, JSONException {
  ArrayList<ToDoItem> items = new ArrayList<>();
  BufferedReader bufferedReader = null;
  FileInputStream fileInputStream = null;
  try {
    fileInputStream = mContext.openFileInput(mFileName);
    StringBuilder builder = new StringBuilder();
    String line;
    bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
    while ((line = bufferedReader.readLine()) != null) {
      builder.append(line);
    }
    JSONArray jsonArray = (JSONArray) new JSONTokener(builder.toString()).nextValue();
    for (int i = 0; i < jsonArray.length(); i++) {
      ToDoItem item = new ToDoItem(jsonArray.getJSONObject(i));
      items.add(item);
    }
  } catch (FileNotFoundException fnfe) {
    //do nothing about it
    //file won't exist first time app is run
  } finally {
    if (bufferedReader != null) {
      bufferedReader.close();
    }
    if (fileInputStream != null) {
      fileInputStream.close();
    }
  }
  return items;
}

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

try {
        final JSONObject json = new JSONObject(result);
        final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
        final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
        final JSONArray steps = leg.getJSONArray("steps");
        final int numSteps = steps.length();
        route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
            final JSONObject step = steps.getJSONObject(i);
            final JSONObject start = step.getJSONObject("start_location");
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
  while ((line = reader.readLine()) != null) {
    sBuf.append(line);

代码示例来源:origin: ron190/jsql-injection

InputStream in = ManagerScan.class.getResourceAsStream("/com/jsql/view/swing/resources/list/scan-page.json");
  String line;
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  while ((line = reader.readLine()) != null) {
    jsonScan.append(line);
  reader.close();
} catch (IOException e) {
  LOGGER.error(e.getMessage(), e);
JSONArray jsonArrayScan = new JSONArray(jsonScan.toString());
for (int i = 0 ; i < jsonArrayScan.length() ; i++) {
  JSONObject jsonObjectScan = jsonArrayScan.getJSONObject(i);
  BeanInjection beanInjection = new BeanInjection(
    jsonObjectScan.getString("url"),
    jsonObjectScan.optString("request"),
    jsonObjectScan.optString("header"),
    jsonObjectScan.optString("injectionType"),
    jsonObjectScan.optString("vendor"),

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

DefaultHttpClient httpClient = new DefaultHttpClient();
  response = httpClient.execute(req);
 if (response.getStatusLine().getStatusCode() == 200) {
                   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
                   StringBuilder sb = new StringBuilder();
                   while ((line = bufferedReader.readLine()) != null) {
                   sb.append(line + "\n");
                   Log.d("result:",result.toString());
                   JSONObject jsonResponse = new JSONObject(result);
                    JSONArray array = jsonResponse.optJSONArray("Android");
                    for(int i=0;i<array.length();i++){
                      String strJSONobj=array.getString(i);
                      JSONObject json = new JSONObject(strJSONobj);                                           
                      Log.d("result",json.getString("id"));
                      Log.d("result",json.getString("title"));

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

DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has("lessons")) {
  JSONArray jsonLessons = jsonObject.getJSONArray("lessons");
  List<Lesson> lessons = new ArrayList<Lesson>();
  for(int i = 0; i < jsonLessons.length(); i++) {
    JSONObject jsonLesson = jsonLessons.get(i);
    // Use optString instead of get on the next lines if you're not sure
    // the fields are always there
    String name = jsonLesson.getString("name");
    String teacher = jsonLesson.getString("prof");
    lessons.add(new Lesson(name, teacher));
  }
}

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

CloseableHttpClient httpClient = HttpClients.custom().build();
   HttpPost getRequest = new HttpPost("http://search.maven.org/solrsearch/select?q=1:<JAR CHECKSUM>&rows=1&wt=json");
   getRequest.addHeader("accept", "application/json");
   HttpResponse response = httpClient.execute(getRequest);
   if (response.getStatusLine().getStatusCode() != 200) {
     throw new RuntimeException("Failed : HTTP error code : "
         + response.getStatusLine().getStatusCode());
   }
   BufferedReader br = new BufferedReader(new InputStreamReader(
       (response.getEntity().getContent())));
   String output;
   StringBuffer outputBuffer = new StringBuffer("");
   while ((output = br.readLine()) != null) {
     outputBuffer.append(output);
   }
   JSONObject jsonObj = new JSONObject(outputBuffer.toString());
   LOGGER.info("MAVEN Compatible Dependency Found: " + jsonObj.getJSONObject ("response").getInt("numFound"));
   if (jsonObj.getJSONObject ("response").getInt("numFound") > 1) {
     JSONArray jsonArray = jsonObj.getJSONObject ("response").getJSONArray("docs");
     JSONObject object = (JSONObject) jsonArray.get(0);
     LOGGER.info(object.getString("g"));
     LOGGER.info(object.getString("a"));
     LOGGER.info(object.getString("v"));
   }

代码示例来源:origin: apache/incubator-gobblin

private void fillServerPort()
{
 try {
  URL url = new URL("http://localhost:" + _port + "/pools/default/buckets");
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setRequestProperty("Accept", "application/json");
  httpURLConnection.setRequestMethod("GET");
  if (200 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 299) {
   BufferedReader br = new BufferedReader(new InputStreamReader((httpURLConnection.getInputStream())));
   StringBuilder sb = new StringBuilder();
   String output;
   while ((output = br.readLine()) != null) {
    sb.append(output);
   }
   JSONArray json = new JSONArray(sb.toString());
   log.debug(json.toString());
   int serverPort =
     (Integer) ((JSONObject) ((JSONObject) ((JSONArray) ((JSONObject) json.get(0)).get("nodes")).get(0)).get("ports")).get("direct");
   _serverPort = serverPort;
  }
 }
  catch (Exception e) {
   log.error("Server is not up", e);
   Throwables.propagate(e);
  }
}

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

DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpResponse httpResponse = httpClient.execute(httpGet);
   HttpEntity httpEntity = httpResponse.getEntity();
   is = httpEntity.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");
   JSONObject jObj = new JSONObject(sb.toString());
   JSONArray json2 = json.getJSONArray("user");
   for (int i = 0; i < json2.length(); i++) {
     JSONObject c = json2.getJSONObject(i);

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

HttpClient httpclient = new DefaultHttpClient();
String url = "https://graph.facebook.com/me/friends?access_token=" + URLEncoder.encode(token);
HttpGet httppost = new HttpGet(url);
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        for (String line = null; (line = reader.readLine()) != null;) {
          res += line + "\n";
        JSONArray data = obj.getJSONArray("data");
int len = data.length();
for (int i = 0; i < len; i++) {
          JSONObject currentResult = data.getJSONObject(i);
          String name = currentResult.getString("name");
          String icon = currentResult.getString("id");

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

httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);           
HttpEntity entity = response.getEntity();
} catch (Exception e) {
  Log.e("log_tag", "Error in http connection " + e.toString());
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
  StringBuilder sb = new StringBuilder();
  while ((line = reader.readLine()) != null)
  JSONArray jArray = new JSONArray(result);
 List<String> list = new ArrayList<String>();
 for (int i = 0; i < jArray.length(); i++)
 { JSONObject json_data = jArray.getJSONObject(i); 
  list.add(json_data.getString("url"));

相关文章