Pieter De Rop
Pieter De Rop

Reputation: 43

Get value out JSON Object containing JSON arrays

How can I get the value of "distance" out of the following JSON object with java?

{
  "destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
  "origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
  "rows" : [
    {
       "elements" : [
          {
             "distance" : {
                "text" : "225 mijl",
                "value" : 361714
             },
             "duration" : {
                "text" : "3 uur 51 min.",
                "value" : 13877
             },
             "status" : "OK"
          }
       ]
    }
 ],
 "status" : "OK"
}      

I tried: json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();

But I always get org.json.JSONException: JSONObject["distance"] not found.

Upvotes: 0

Views: 667

Answers (2)

Rafael Passarela
Rafael Passarela

Reputation: 156

I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.

Try this:

json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();

Again, I think. I hope this helped you.

Upvotes: 2

PVR
PVR

Reputation: 915

Use java-json.jar

Convert JSON String to object and fetch the element.

You can refer this.

Try this:

package Sample;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TestMain 
{

    public static void main(String[] args) throws JSONException
    {
        String s="{  \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ],  \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ],  \"rows\" : [    {       \"elements\" : [          {             \"distance\" : {                \"text\" : \"225 mijl\",                \"value\" : 361714             },             \"duration\" : {                \"text\" : \"3 uur 51 min.\",                \"value\" : 13877             },             \"status\" : \"OK\"          }       ]    } ], \"status\" : \"OK\"} ";

        JSONObject jsonObj = new JSONObject(s);

        JSONArray array= (JSONArray) jsonObj.get("rows");

        JSONObject jsonObj2 =(JSONObject) array.get(0);

        JSONArray array2= (JSONArray)jsonObj2.get("elements");

        JSONObject jsonObj3 =(JSONObject) array2.get(0);

        System.out.println(jsonObj3.get("distance"));

    }
}

OUTPUT:

{"text":"225 mijl","value":361714}

Upvotes: 0

Related Questions