2012-02-21 73 views
1

我想從json獲取經度&緯度。爲此,我使用Google Maps API獲取json,然後將其放入JsonElement中,但現在我無法弄清楚如何讀取此值(緯度,經度)。消耗解析的json與玩!框架

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 
     } 
     } 
    } 
    } ] 
} 

任何建議嗎?

回答

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

的偉大工程!非常感謝 – Mooh 2012-02-21 22:00:14