Sid Rampally Sid Rampally - 3 months ago 21
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("") + "";
String lng = latlong.getInt("results.geometry.location.lng") + "";

Here is a link to the JSON Data:

Please Help!


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")

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