Android JSONException "no value for key"
Android JSONException "no value for key"
我正在从这样的网站获取一个 JSON 对象:
JSONObject response = new JSONObject(read(placeConnection));
当我执行 response.toString();
时,我得到了那个 JSON 对象的整个字符串,我想要的键和值就在那里。
但是,当我执行 response.getString("countryName")
时,出现上述异常,它说该键没有值。
这是字符串形式的 JSON:
{"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}]}
这是错误:
org.json.JSONException: No value for countryName
您的字段在数组结构中,因此您在第一层的 getString 不起作用。
你需要做类似(未测试)的事情:
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
}
我正在从这样的网站获取一个 JSON 对象:
JSONObject response = new JSONObject(read(placeConnection));
当我执行 response.toString();
时,我得到了那个 JSON 对象的整个字符串,我想要的键和值就在那里。
但是,当我执行 response.getString("countryName")
时,出现上述异常,它说该键没有值。
这是字符串形式的 JSON:
{"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}]}
这是错误:
org.json.JSONException: No value for countryName
您的字段在数组结构中,因此您在第一层的 getString 不起作用。
你需要做类似(未测试)的事情:
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
}