Note that there are some explanatory texts on larger screens.

plurals
  1. POMost Efficient Way to Parse JSON Using Android
    text
    copied!<p>I've written some code to parse the Google Distance Matrix JSON response received by my Android program. The only piece of data I'm interested in is in the "distance" "value" node. </p> <p>My code works, but it seems like there must be an easier way to do this. The distance value node is nested pretty deep inside the JSON, but is it really necessary to go through every layer of the JSON to get to the field you want?</p> <p>Here's my JSON response:</p> <pre><code>{ "destination_addresses" : [ "5660 Baltimore National Pike, Ingleside Shopping Center, Catonsville, MD 21228, USA" ], "origin_addresses" : [ "Hilltop Cir, Baltimore, MD 21250, USA" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "3.1 mi", "value" : 4922 &lt;--THE FIELD I WANT TO EXTRACT }, "duration" : { "text" : "11 mins", "value" : 666 }, "status" : "OK" } ] } ], "status" : "OK" } </code></pre> <p>And here is the code I used to pull out the distance value:</p> <pre><code> private double extractDistance(JSONObject json) { JSONArray rowsArray = null; double distanceInMiles = -1; try { // Getting Array of Distance Matrix Results rowsArray = json.getJSONArray("rows"); JSONObject rowsObject = rowsArray.getJSONObject(0);//only one element in this array JSONArray elementsArray = rowsObject.getJSONArray("elements"); JSONObject elementsObject = elementsArray.getJSONObject(0);//only one element in this array JSONObject distanceObject = elementsObject.getJSONObject("distance"); distanceInMiles = (distanceObject.getDouble("value"))/1609.344; //distance in meters converted to miles } catch (JSONException e) { e.printStackTrace(); } return distanceInMiles; } </code></pre> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload