I'm trying to get the value of elevations from JSON in android but in the log nothing is shown. This JSON is a nested array, I'm still new toth parsing JSON in android.

This is what the JSON looks like :

enter image description here

This is my code :

try {
      JSONObject responseObject = new JSONObject(result);
      JSONArray elev = responseObject.getJSONArray("resourceSets");
      JSONArray el = elev.getJSONObject(1).getJSONArray("elevations");

      for(int i=0; i<=el.length();i++){
           Log.d("EL",el.toString());
      }
}
catch (Exception e){
    e.printStackTrace();
}

1 Answers

2
android On Best Solutions

try like below: (problem in your code is you are getting "elevations" directly without getting "resources" array)

try {
      JSONObject responseObject = new JSONObject(result);
      JSONArray elev = responseObject.getJSONArray("resourceSets");
      JSONArray el_resources = elev.getJSONObject(0).getJSONArray("resources");
      JSONArray el = el_resources.getJSONObject(0).getJSONArray("elevations");

      for(int i=0; i<=el.length();i++){
           Log.d("EL", el[i].toString()); // also get index from array then print it
      }
}
catch (Exception e){
    e.printStackTrace();
}