hany mhajna hany mhajna - 1 month ago 17
Android Question

can't take any element from JSONObject in java

i have problem with taking element from JSONObject.

this is my code :

public static void getJSON(){
String googlemap = "http://maps.googleapis.com/maps/api/geocode/json?address=29.0+35.0&sensor=true";

HttpResponse httpRespone = GET.sendGetReq(googlemap);
try {
//Get Stream and convert it to String
String inputStreamAsString = convertStreamToString(httpRespone.getEntity().getContent());

//convert from String to JSONObject
JSONObject json = new JSONObject(inputStreamAsString);
String formatted_address = json.getJSONObject("results").getString("formatted_address");


} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


when i called to

String formatted_address = json.getJSONObject("results").getString("formatted_address");


i get JSONException...

my json is here :
http://maps.googleapis.com/maps/api/geocode/json?address=29.0+35.0&sensor=true
json link

and i want to take the value of "formatted_address".
can you please help me ?

Answer

results is a JSONArray

{} this is a JSONObject

[] this is a JSONArray, that can contain X JSONObjects, wich you can access either by a for loop, or with the index (if you know it)

String formatted_address  = json.getJSONArray("results").getJSONObject(0).getString("formatted_address");