1

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 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

wah thank you, its work. Can you tell me why that JSONObject at index 0?
JSONObject at index 0 means we are getting 0th index from array but if you have multiple json array then you can for loop it

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.