我有来自谷歌地图的以下JSON响应。我给了两个邮政编码作为开始和目的地。它描述了响应中的路由,以便部分正常工作。我想从响应中获取经度和纬度,以便我可以加载相应的地图。我遇到的问题是“东北”属性无法找到,有什么想法吗?
02-05 18:50:03.668: E/*********HelloviewActivity(10381): response code OK
02-05 18:50:03.673: E/*********HelloviewActivity(10381): {
02-05 18:50:03.673: E/*********HelloviewActivity(10381): "routes" : [
02-05 18:50:03.673: E/*********HelloviewActivity(10381): {
02-05 18:50:03.673: E/*********HelloviewActivity(10381): "bounds" : {
02-05 18:50:03.673: E/*********HelloviewActivity(10381): "northeast" : {
02-05 18:50:03.678: E/*********HelloviewActivity(10381): "lat" : 53.654430,
02-05 18:50:03.678: E/*********HelloviewActivity(10381): "lng" : -1.778250
02-05 18:50:03.678: E/*********HelloviewActivity(10381): },
02-05 18:50:03.678: E/*********HelloviewActivity(10381): "southwest" : {
02-05 18:50:03.683: E/*********HelloviewActivity(10381): "lat" : 53.62041000000001,
02-05 18:50:03.683: E/*********HelloviewActivity(10381): "lng" : -1.831710
02-05 18:50:03.683: E/*********HelloviewActivity(10381): }
02-05 18:50:03.683: E/*********HelloviewActivity(10381): },
String jsonOutput = response.toString();
// Log.e(TAG,"jsonOutput = " + jsonOutput);
JSONObject results = null;
try {
results = new JSONObject(jsonOutput);
routes = results.getJSONArray("routes");
bounds = routes.getJSONObject(0);
northeast = bounds.getJSONObject("northeast");
lat = Double.parseDouble((String) northeast.get("lat"));
lon = Double.parseDouble((String) northeast.get("lng"));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(TAG, "lon/lat = "+lon +" "+lat);
02-05 18:50:04.668: W/System.err(10381): org.json.JSONException: JSONObject["northeast"] not found.
答案 0 :(得分:2)
routes
是包含 bounds
对象的(匿名)对象数组。
anonObject = routes.getJSONObject(0);
bounds = anonObject.getJSONObject("bounds");
修改:此外 - 一旦获得bounds
对象; lat
和lng
不是String
s - 它们已经Double
s - 您没有进行任何转换:
lat = bounds.getDouble("lat");
lon = bounds.getDouble("lng");