我的版本是Android 2.2 Google API 8,我是从模拟器运行的。我正在尝试在此JSON对象中尝试访问位置。我使用
后得到这个 InputStream instream = entity.getContent();
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
Google文档说它会返回一个数组,但周围有花括号它看起来像一个对象。
我需要在位置字段中访问lat和lon并存储为双精度。
我已经搜索过,但似乎只能找到简单文件的帮助。
{
"results" : [
{
"address_components" : [
{
"long_name" : "20059",
"short_name" : "20059",
"types" : [ "postal_code" ]
},
{
"long_name" : "Washington D.C.",
"short_name" : "Washington D.C.",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Washington D.C., DC 20059, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 38.924920,
"lng" : -77.0178720
},
"southwest" : {
"lat" : 38.9189910,
"lng" : -77.02261200000001
}
},
"location" : {
"lat" : 38.92177780,
"lng" : -77.01974260
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 38.92510312068017,
"lng" : -77.01709437931984
},
"southwest" : {
"lat" : 38.91880787931983,
"lng" : -77.02338962068018
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
答案 0 :(得分:4)
JSONObject jObject = new JSONObject(convertStreamToString(instream));
JSONArray results = jObject.getJSONArray("result");
JSONObject geometry = results.getJSONObject(2);
JSONObject bounds = geometry.getJSONObject("bounds");
JSONObject northeast = geometry.getJSONObject("northeast");
double nLat = Double.parseDouble(northeast.getString("lat").toString());
double nLng = Double.parseDouble(northeast.getString("lng").toString());
那应该给你东北的lat / lng作为双打。东南部就像东南部一样取代东北部。
答案 1 :(得分:2)
JSONObject location = myAwway.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
'结果'JSONArray可能是Google文档建议的数组。他们刚刚将其包装在具有状态的JSONObject中,以便您可以在尝试处理返回的值之前检查状态。