简体   繁体   中英

JSONArray from JSONArray in java

I need to get JSONArray from 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.

My JSON string:

    {
   "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. Arrays don't have any attribute. They have elements, indexed from 0 to the length of the array.

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:

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.

JSONArray objects have a function getJSONObject(int index) .

You can get all JSONObjects by writing a simple for-loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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