简体   繁体   English

Java中的JSONArray中的JSONArray

[英]JSONArray from JSONArray in java

I need to get JSONArray from JSONArray: 我需要从JSONArray获取JSONArray:

      JSONParser parser = new JSONParser();
      JSONObject jObject=(JSONObject)parser.parse(s);
      JSONArray messages = (JSONArray) jObject.get("routes");
      JSONArray ar = (JSONArray)messages.get("legs");

JSONArray.get don't take string as parameter. JSONArray.get不要将字符串作为参数。

My JSON string: 我的JSON字符串:

    {
   "routes" : [
  {
     "bounds" : {
        "northeast" : {
           "lat" : 27.9786758,
           "lng" : 31.2199858
        },
        "southwest" : {
           "lat" : 27.0120443,
           "lng" : 30.9788969
        }
     },
     "copyrights" : "Map data ©2015 Google, ORION-ME",
     "legs" : [
        {
           "distance" : {
              "text" : "138 km",
              "value" : 138208
           },
           "duration" : {
              "text" : "1 hour 52 mins",
              "value" : 6744
           },

A JSONArray represents an array. JSONArray表示一个数组。 Arrays don't have any attribute. 数组没有任何属性。 They have elements, indexed from 0 to the length of the array. 它们具有从0到数组长度的索引的元素。

If you want to get the first element, which is a JSONObject having a legs attribute, from the array, then use something like the following: 如果要从数组中获取第一个元素(具有legs属性的JSONObject),请使用类似以下内容的方法:

JSONObject firstElement = (JSONObject) messages.get(0);
JSONArray ar = (JSONArray) firstElement.get("legs");

The exact method names might vary: there are dozens of JSON libraries out there, and you didn't tell which one you were using. 方法的确切名称可能有所不同:那里有数十个JSON库,您没有告诉您使用的是哪个。

JSONArray objects have a function getJSONObject(int index) . JSONArray对象具有函数getJSONObject(int index)

You can get all JSONObjects by writing a simple for-loop: 您可以通过编写一个简单的for循环来获取所有JSONObjects

JSONArray messages = (JSONArray) jObject.get("routes");
for(int n = 0; n < messages.length(); n++)
{
    JSONObject object = messages.getJSONObject(n);
    JSONArray legs = (JSONArray) object .get("legs");
    // do your stuff....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM