Java JSONObject获取子项

我想在我的网站上创建gmaps。

我找到了,如何获得坐标。

{ "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-simple

  com.googlecode.json-simple json-simple 1.1  

我的代码是:

 String coordinates = //JSON from google JSONObject json = (JSONObject)new JSONParser().parse(coordinates); 

我可以得到第一个孩子:“结果”

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

json2显示正确的“结果”正文

但我不能得到“位置”的孩子。

怎么做 ?

谢谢

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

 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部分的类型,并将其转换为适当的类型。