7

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.

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?

Here's my JSON response:

{
"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 <--THE FIELD I WANT TO EXTRACT
           },
           "duration" : {
              "text" : "11 mins",
              "value" : 666
           },
           "status" : "OK"
        }
     ]
  }
],
"status" : "OK"
}

And here is the code I used to pull out the distance value:

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

Thanks!

1
  • 2
    "but is it really necessary to go through every layer of the JSON to get to the field you want?" Yes - unless the json is not changing much then you could get to that data with some String manipulation (jsonResponse.firstIndexOf("\"distance\"") etc.). But it's way safer to stay with the method you currently use. Commented Mar 12, 2012 at 15:36

5 Answers 5

6

I recommend you GSON (http://code.google.com/p/google-gson/) which parse the JSON text into a java class instance, and can convert the class instance to JSON text

Sign up to request clarification or add additional context in comments.

1 Comment

At first glance, this seems a little more complicated than json-path recommended above. But I'll read the documentation more closely and see if I can figure it out. Thanks!
6

Jackson is another good third party parser http://jackson.codehaus.org/. Looks like there's a comparison here, http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html.

Here's an example traversing using a tree, not sure if it qualifies as easier then what you are already doing, http://wiki.fasterxml.com/JacksonTreeModel

2 Comments

Interesting. Lots of options out there. I'll have to read up on this as well. Thanks!
Not just tree model, but it can use JSON Pointer expressions (see JsonNode.at(jsonPointerExpression). So, something like: JsonNode root = mapper.readTree(...); int value = root.at("/rows/1/elements/1/distance/value").asIntValue();
3

Unless you want to go into writing a custom regular expression to search the json string, yes that's going to be the best way of accessing it (and the easiest). Is there a reason you feel you need to access it 'more efficiently'?

4 Comments

No real need to access the node-of-interest more efficiently, it just seems like it should be easier. But I guess the "built-in" way of getting the field I want does require a few steps.
Then you should really stick to your current method. It's far more readable and reliable. And most likely far faster than converting it into an actual java object.
In the end, I ended up using the code I had written, which drops through every node in the JSON. I still maintain it's harder to parse than it should be!
Regexp would be a bad idea for multiple reasons (escaping etc), and not even necessarily more efficient than proper JSON library. As to ease, Jackson and GSON do offer much more convenient and efficient ways.
3

If you are willing to include a third party library you might check out http://code.google.com/p/json-path/ .

1 Comment

I'll look into this as an option. From the link you gave, that seems to be the type of simpler JSON navigation I was envisioning. Thanks!
2

I know what you feel right now, I had / have same issues with JSON parsing on android where we dont have @getValueforKey kind of features which is embedded on iOS, Even its so obivious google should realize it now, But there is good work done on Gson lib., look for Google Gson Here for easy way to parse json

Here is nice tute : Gson tute

1 Comment

Tell me about it, even the JSON in their example isn't valid: developer.android.com/reference/android/util/JsonReader.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.