2014-06-09 77 views
3

我想在我的网站上创建gmaps。Java JSONObject获取子女

我发现,如何获得坐标。

{ 
    "results" : [ 
     { 
     // body 
     "formatted_address" : "Puławska, Piaseczno, Polska", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 52.0979041, 
        "lng" : 21.0293984 
       }, 
       "southwest" : { 
        "lat" : 52.0749265, 
        "lng" : 21.0145743 
       } 
      }, 
      "location" : { 
       "lat" : 52.0860667, 
       "lng" : 21.0205308 
      }, 
      "location_type" : "GEOMETRIC_CENTER", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 52.0979041, 
        "lng" : 21.0293984 
       }, 
       "southwest" : { 
        "lat" : 52.0749265, 
        "lng" : 21.0145743 
       } 
      } 
     }, 
     "partial_match" : true, 
     "types" : [ "route" ] 
     } 
    ], 
    "status" : "OK" 
} 

我想:

"location" : { 
      "lat" : 52.0860667, 
      "lng" : 21.0205308 
     }, 

从这JSON。

我决定用户JSON-简单

<dependency> 
     <groupId>com.googlecode.json-simple</groupId> 
     <artifactId>json-simple</artifactId> 
     <version>1.1</version> 
    </dependency> 

我的代码是:

String coordinates = //JSON from google 

JSONObject json = (JSONObject)new JSONParser().parse(coordinates); 

,我可以得到的第一批孩子: “结果”

String json2 = json.get("results").toString(); 

json2显示正确“结果”的主体

但我无法获得“位置”儿童。

怎么办?

感谢

回答

8

我认为你需要调用转换为json.get("results")JSONArray

I.e.

String coordinates = //JSON from google 

JSONObject json = (JSONObject)new JSONParser().parse(coordinates); 

JSONArray results = (JSONArray) json.get("results"); 

JSONObject resultObject = (JSONObject) results.get(0); 

JSONObject location = (JSONObject) resultObject.get("location"); 

String lat = location.get("lat").toString(); 

String lng = location.get("lng").toString() 

诀窍是看看你的反序列化json的部分是什么类型,并将其转换为适当的类型。