[英]consuming parsed json with play! framework
I want to get longitude & latitude from a json. 我想从json获取经度和纬度。 to do so i use the Google Maps API to get the json then i put it into a JsonElement but now i can't figure out how to read this values (latitude, longitude).
为此,我使用Google Maps API获取json,然后将其放入JsonElement中,但现在我不知道如何读取此值(纬度,经度)。
public static void getGeo(){
HttpResponse res = WS.url("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true").get();
int status = res.getStatus();
String type = res.getContentType();
JsonElement json = res.getJson();
JsonObject jsonObject = json.getAsJsonObject();
//with a system out i can see that the json is parsed correctly
System.out.print(jsonObject.get("results"));
}
the parsed json: 解析的json:
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": [ "route" ]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "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" ]
} ],
"geometry": {
"location": {
"lat": 37.4219720,
"lng": -122.0841430
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188244,
"lng": -122.0872906
},
"northeast": {
"lat": 37.4251196,
"lng": -122.0809954
}
}
}
} ]
}
any suggestion please ? 有什么建议吗?
This should do the trick for you: 这应该为您解决问题:
HttpResponse res = WS.url("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true").get();
JsonElement json = res.getJson();
System.out.println("JSON: " + json);
//with a system out i can see that the json is parsed correctly
JsonArray jsArr = json.getAsJsonObject().getAsJsonArray("results");
for (JsonElement jsEl : jsArr)
{
JsonObject locationObject = jsEl.getAsJsonObject().getAsJsonObject("geometry").getAsJsonObject("location");
double lat = locationObject.getAsJsonPrimitive("lat").getAsDouble();
double lng = locationObject.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("Lat is " + lat + " and lng is " + lng);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.