parse json object response from php web service
i have gone through a number of tutorials to get an idea as to how can we parse JSON object. the structure of ma JSON object response from web service is like this
{"posts":[
{"gpoint":{"latitude":"18.966364","longitude":"72.811317"}},
{"gpoint":{"latitude":"19.07023","longitude":"72.82917"}},
{"gpoint":{"latitude":"19.094889","longitude":"72.840157"}},
{"gpoint":{"latitude":"19.056601","longitude":"72.901955"}}]
}
and this is my code:
HttpResponse response= client.execute(post);
content = response.getEntity().getContent();
String result = stringConversion(content);
jObject = new JSONObject(result);
JSONArray gpoint = jObject.getJSONArray("posts");
for (int i = 0; i<gpoint.length();i++)
{
double geoLat=gpoint.getJSONObject(i).optDouble("latitude");
double geoLong=gpoint.getJSONObject(i).optDouble("longitude");
// double geoLat = gPointObject.getDouble("latitude");
// double geoLong = gPointObject.getDouble("longitude");
Log.i(Tag," "+ geoLat);
Log.i(Tag," "+ geoLong);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
开发者_JS百科
I am not able to parse this response, whenever I am parsing it, it does not give any parse exception but the value for latitude and longitude is NaN
Kindly tell me, where am I going wrong? Thanks in advance.
Try this:
JSONObject gp;
for (int i = 0; i<gpoint.length();i++)
{
gp = gpoint.getJSONObject(i);
double geoLat = gp.getJSONObject("gpoint").optDouble("latitude");
double geoLong = gp.getJSONObject("gpoint").optDouble("latitude");
// double geoLat = gPointObject.getDouble("latitude");
// double geoLong = gPointObject.getDouble("longitude");
Log.i(Tag," "+ geoLat);
Log.i(Tag," "+ geoLong);
}
You're missing one nesting layer.
You may want to use GSON. If you prepare adequate DTO structure, you can map your JSON in one function call. I'm using it in my app.
精彩评论