請幫助,這是我第一次使用JSON/GSON。 我從Google地理編碼API獲取了此JSON數據,但無法弄清楚如何從中提取「formatted_address」。在java中使用GSON從JSON中提取數據
{
"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";
}
可以創建對應於上述JSON響應一個豆,然後解析到一個Java bean上述響應。 –
當你想解決一個異常時,建議包含它的堆棧跟蹤,這樣我們可以很容易地檢查錯誤發生的位置以及在哪個上下文中,而不必讀取整個代碼並猜測錯誤是什麼。 – Aaron
在這種情況下,它看起來像'results'數組只包含一個元素,這就解釋了爲什麼調用'get(1)'會失敗。我想你想寫'get(0)'(Java中的數組是0-索引) – Aaron