用游戏消费解析的json!骨架

时间:2012-02-21 20:36:47

标签: java json parsing playframework

我想得到经度&来自json的纬度。这样做我使用谷歌地图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"));
}

解析的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
        }
      }
    }
  } ]
}

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

这应该适合你:

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);
}