Pieter De Rop Pieter De Rop - 5 months ago 8
JSON Question

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.

Answer

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 them take the object 0 again, soooo 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.

Comments