1

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

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.

2 Answers 2

3

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.

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

1 Comment

Glad to help. It happens all the time: you are sitting so close to the problem you don't notice your mistake.
0

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.

Comments

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.