Parsing json response from google direction api

2019-08-04 17:59发布

问题:

I'm trying to parse the JSON response from google direction api in my android program. This is the request link bellow. I'm skipping the JSON response here because its too long and simply clicking on the link will show it.

http://maps.googleapis.com/maps/api/directions/json?origin=Windsor&destination=Leamington&sensor=false&avoid=highways&mode=walking

My code for parsing the response :

try {
    JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
    this.responseString = responseObject.getString("status") ;
    JSONArray routesArray = responseObject.getJSONArray("routes");
    JSONObject route = routesArray.getJSONObject(0);
    JSONArray legs ;
    JSONObject leg ;
    JSONArray steps ;
    JSONObject dist;
    Integer distance ;
    if(route.has("legs")) {
        legs = route.getJSONArray("legs");
        leg = legs.getJSONObject(0) ;
        steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
        int nsteps = steps.length() ;
        for(int i=0;i<nsteps;i++) {
        JSONObject step = steps.getJSONObject(i);
            if(step.has("distance")) {
                dist = (JSONObject) step.get("distance");// throws exception
                //I would like to take the distance value and do something with it
                //if(dist.has("value"))
                //  distance = (Integer) dist.get("value") ;
            }
        }
    }
    else
        this.responseString = "not found" ;
} catch ( Exception e) {
    e.printStackTrace() ;
}

This throws an exception (again skipping because the JSON response is too big. The stack trace shows the entire response string) :

org.json.JSONException: Expected ':' after polyline at character 13837 of {
    "routes" : [
       {
          "bounds" : {
             "northeast" : { ....

I have tried using the getJSONObject function instead of get, but I get the same exception.

dist = step.getJSONObject("distance");

Can anyone please help me by pointing out what am I missing here ? I'm not very familiar with parsin JSON on android yet, so it's quite likely that I'm making a silly mistake somewhere. Thanks.

Another similar post on this site, but not quite the same : JSON parsing of Google Maps API in Android App

回答1:

As you aren't so familiar, i'd suggest parsing JSON using Gson, esp for complex responses. The case would suit better in your case.

I have used Gson for parsing responses from Google Maps API, Places API and more...

You may be better off using Gson to parse, map data and your model classes. Eg.:

    Gson gson = new Gson();
    ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
    modelClass= gson.fromJson(responseContent,ModelClass.class); 
//where responseContent is your jsonString
    Log.i("Web service response", ""+modelClass.toString());

https://code.google.com/p/google-gson/

For Naming discrepancies(according to the variables in webservice), can use annotations like @SerializedName. (So no need to use Serializable)

You can use a for-each loop and verify or operate the data from the model classes.

for(Modelclass object: modelClass.getList()) {
}

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

How does the Java 'for each' loop work?

Also, use a for-each instead of for(;;) where ever possible.

Check these:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json

I am working on the same API right now, thought this would also help, for the model classes:
Displaying multiple routes using Directions API in Android



回答2:

Try this..

    steps = leg.getJSONArray("steps");
    int nsteps = steps.length() ;
    for(int i=0;i<nsteps;i++) {
        if(steps.has("distance")) {
            JSONObject new_onj = steps.getJSONObject(i);
            dist = new_onj.getJSONObject("distance");       
            if(dist.has("value"))
               distance = (Integer) dist.get("value");
        }
    }


回答3:

Your for loop never sets a value for step - are you missing a line

step = steps.getJSONObject(i);

at the top of your for loop?