使用Gson解析Json而没有POJO?
希望这里有一个简单的解决方案。我知道有类似的问题,但我似乎无法修改它们以解决我的问题。
我正在尝试解析此json响应中“formatted_address”的字符串:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Google Building 42",
"short_name" : "Google Bldg 42",
"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 42, 1600 Amphitheatre Pkwy, Mountain
View, CA 94043, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 37.42198310000001,
"lng" : -122.0853195
},
"southwest" : {
"lat" : 37.4214139,
"lng" : -122.0860042
}
},
"location" : {
"lat" : 37.4216548,
"lng" : -122.0856374
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4230474802915,
"lng" : -122.0843128697085
},
"southwest" : {
"lat" : 37.4203495197085,
"lng" : -122.0870108302915
}
}
},
"place_id" : "ChIJPzxqWQK6j4AR3OFRJ6LMaKo",
"types" : [ "premise" ]
}
],
"status" : "OK"
}
以前使用gson时,我能够立即使用以下命令解析结果:
Gson gson = new Gson();
JsonArray body = gson.fromJson(ResultString, JsonArray.class);
System.out.println(body.get(0).getAsJsonObject().get("elementnamehere").getAsString());
主要区别在于我无法将此结果放入 JsonArray 正文中。相反(我相信因为它有嵌套数据),我必须使它成为JsonObject,但是我无法在不获得Null的情况下解析它。有什么简单的方法可以在不制作POJO或响应类的情况下做到这一点吗?如果不是,有人可以解释如何/为什么这样做: