Kingamere Kingamere - 28 days ago 8
Android Question

Android JSONException "no value for key"

I am a getting a JSON object from a website like this:

JSONObject response = new JSONObject(read(placeConnection));


and when I execute
response.toString();
I get the entire String for that JSON object and the key and value that I want is in there.

However, when I execute
response.getString("countryName")
I get the above exception and it says there is no value for that key.

Here is the JSON in String form:

{"geonames":[{"countryId":"6252001","countryName":"United States","adminCode1":"NC","fclName":"city, village,...","countryCode":"US","lng":"-76.98661","fcodeName":"populated place","toponymName":"Riverdale","distance":"1.30053","fcl":"P","name":"Riverdale","fcode":"PPL","geonameId":4488145,"lat":"34.99599","adminName1":"North Carolina","population":0}]}


Here is the error:

org.json.JSONException: No value for countryName

Answer

Your field is inside an array structure, so your getString on first level does not work.

You need to do something like (untested):

JSONArray geonames = response.getJSONArray("geonames");
for(int i = 0 ; i < geonames.length() ; i++){
    JSONObject geo = (JSONObject)geonames.get(i);
    String countryName = geo.getString("countryName");

    // Do something with it
}
Comments