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