我正在尝试从JSON中的位置获取纬度和经度项,但我在Android上获得了一个超出范围的数组异常。
这是JSON文件:
{
"results" : [
{
"address_components" : [
{
"long_name" : "21211",
"short_name" : "21211",
"types" : [ "postal_code" ]
},
{
"long_name" : "Baltimore",
"short_name" : "Balt",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Maryland",
"short_name" : "MD",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Baltimore, MD 21211, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
},
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
}
},
"place_id" : "ChIJn-Z5WtQEyIkRQx9CtdQF7-I",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
我只需要两个属性:
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
}
我试过这样做但没有运气:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
JSONObject geometry = results.getJSONObject(2); //ERROR RIGHT HERE!
JSONObject location = geometry.getJSONObject("location");
Double latitude = location.getDouble("lat");
Double longitude = location.getDouble("lng");
答案 0 :(得分:2)
你应该得到JSONObject geometry = results.getJSONObject(0);
,因为数组中只有一个对象。但是,如果我是你,我会创建一个ArrayList
并使用for(int i = 0; i < results.size(); i++)
来获取每个对象以防止出现多个对象,执行以下操作:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
ArrayList<LocationObject> _locationList = new ArrayList<>();
for(int i = 0; i < results.size(); i++){
JSONObject geometry = results.getJSONObject(i).getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
LocationObject _locationObject = new LocationObject();
_locationObject.setLat(location.getDouble("lat"));
_locationObject.setLng(location.getDouble("lng"));
_locationObject.add(_locationObject);
}
答案 1 :(得分:1)
你不能像你那样得到几何图形,因为json对象中的索引2没有对象。 我认为你没有很好地格式化你的json响应。 通过此web site复制您的回复,您就会理解。
以下是一些代码:
JSONObject tmp = results.getJSONObject(0);
JSONObject geometery = tmp.getJSONObject ("geometery");