简体   繁体   中英

How to access deep JSON element in Java

i have the following JSON response:

{
   "destination_addresses" : [ "Berlin, Deutschland" ],
   "origin_addresses" : [ "Mannheim, Deutschland" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "624 km",
                  "value" : 624195
               },
               "duration" : {
                  "text" : "5 Stunden, 53 Minuten",
                  "value" : 21156
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

MY question is: How do I access the "text" Element in the "distance" section?

I have the following right now:

JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
JSONArray rows= null;
rows= object.getJSONArray("rows");

You either have to continue parsing the JSONArray, eg:

for(int i = 0; i < rows.length; i++) {
    JSONArray elements = rows.getJSONArray(i);
    for(int j = 0; j < elements.length; j++) {   
        JSONObject current = elements.getJSONObject(j);
        String curText = current.getJSONObject("distance").getJSONObject("text");
    }    
} 

Or you can represent your Json in a POJO and deserialize it using Jackson's ObjectMapper for example.

i'm not sure but you can try something like that

JSONArray rows = object.getJSONArray("rows");
      for (int i = 0; i < jsonObjInput.length(); i++) {
        JSONObject tmp = jsonObjInput.getJSONObject(i);
       }

Clément

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