Android JSONException“没有键值”

时间:2016-11-06 21:15:03

标签: android json httpurlconnection

我是从这样的网站获取JSON对象:

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

当我执行response.toString();时,我获得了该JSON对象的整个String以及我想要的键和值。

但是,当我执行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

1 个答案:

答案 0 :(得分:3)

您的字段位于数组结构中,因此第一级的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
}