请帮助,这是我第一次使用 JSON/GSON。我从谷歌地理编码 API 获得了这个 JSON 数据,但不知道如何从中提取“formatted_address”。
{
"results" : [
{
"address_components" : [
{
"long_name" : "Google Building 41",
"short_name" : "Google Bldg 41",
"types" : [ "premise" ]
},
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Google Bldg 41, 1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 37.4228642,
"lng" : -122.0851557
},
"southwest" : {
"lat" : 37.4221145,
"lng" : -122.0859841
}
},
"location" : {
"lat" : 37.4224082,
"lng" : -122.0856086
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238383302915,
"lng" : -122.0842209197085
},
"southwest" : {
"lat" : 37.4211403697085,
"lng" : -122.0869188802915
}
}
},
"place_id" : "ChIJxQvW8wK6j4AR3ukttGy3w2s",
"types" : [ "premise" ]
}
],
"status" : "OK"
}
这是我尝试过的,但它抛出 IndexOutOfBoundsException:
public String getLocationData(String location) {
try {
URL url = new URL(location);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser parser = new JsonParser();
JsonElement content = parser.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject jObject = content.getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("results");
jObject = jArray.get(1).getAsJsonObject();
String result = jObject.getAsString();
return result;
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return "fail";
}
我只能在没有堆栈跟踪的情况下猜测您的直接错误是什么,但您正在尝试访问仅包含一项的数组的第二项:
所述results
阵列包含单个元件(一个对象,其字段是address_components
阵列,formatted_address
,geometry
,place_id
和types
)
你试图访问它的第二个元素jArray.get(1)
(Java 中的数组是 0 索引的)
这是一个典型的原因IndexOutOfBoundsException
。
您可能希望访问唯一jArray.get(0)
可以操作的项目,作为JsonObject
您可以访问其字段的项目。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句