我只需要访问“formatted_address”的值:“4 Place du Louvre,75001 Paris,France”属性。请帮助我如何使用com.google.gson.Gson和java执行此操作而不为整个结构维护单独的POJO类。
{
"results": [{
"address_components": [{
"long_name": "4",
"short_name": "4",
"types": ["street_number"]
}, {
"long_name": "Place du Louvre",
"short_name": "Place du Louvre",
"types": ["route"]
}, {
"long_name": "Paris",
"short_name": "Paris",
"types": ["locality", "political"]
}, {
"long_name": "Paris",
"short_name": "75",
"types": ["administrative_area_level_2", "political"]
}, {
"long_name": "Île-de-France",
"short_name": "IDF",
"types": ["administrative_area_level_1", "political"]
}, {
"long_name": "France",
"short_name": "FR",
"types": ["country", "political"]
}, {
"long_name": "75001",
"short_name": "75001",
"types": ["postal_code"]
}],
"formatted_address": "4 Place du Louvre, 75001 Paris, France",
"geometry": {
"location": {
"lat": 48.8600425,
"lng": 2.3412674
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 48.86139148029149,
"lng": 2.342616380291502
},
"southwest": {
"lat": 48.8586935197085,
"lng": 2.339918419708498
}
}
},
"types": ["street_address"]
}],
"status": "OK"
}
我期待下面的解决方案,但是使用gson。
final JSONObject jso = results.getJSONObject(i);
formattedAddress = jso.getString("formatted_address"));
答案 0 :(得分:4)
将String解析为Json元素并获取对象结构
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
要获取对象,请使用:
JsonObject anObject = jobject.getAsJsonObject("object_name");
要获取数组,请使用:
JsonArray jarray = anObject.getAsJsonArray("array_name");
要获取String值,请使用:
String result = anObject.get("property_name").toString();