Sid Rampally Sid Rampally - 10 days ago 5
Android Question

Why can't JSONObject get the values of nested fields in Android?

I am building an android app that gets weather data from an API. However, the API call does not work for nested fields. The app is taking in the entire JSON data as a JSONObject. It works for single fields (ex: "results") but not for nested ones. Here is my JSON Object code:

JSONObject latlong = new JSONObject(json);
String lat = latlong.getInt("results.geometry.location.lat") + "";
String lng = latlong.getInt("results.geometry.location.lng") + "";


Here is a link to the JSON Data:

http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:24728&sensor=false

Please Help!

Answer

JSON is mainly made of objects (enclosed with { }) and arrays (enclosed with []).

Hence, it is necessary to use a combination of JSONObject and JSONArray to go through the tree of the JSON file.

Both JSONObject class and JSONArray have a 'getJSONObject' and a 'getJSONArray' methods to access inner objects and arrays.

So, something like this should work:

    JSONObject latLong = new JSONObject(json).getJSONArray("results")
                                             .getJSONObject("geometry")
                                             .getJSONObject("location");

    String lat = String.valueOf(latLong.getDouble("lat"));
    String lng = String.valueOf(latLong.getDouble("lng"));

Try it and make the right adjustments if needed since I haven't tried it myself.

Let me know if it works ;)