Java JSONObject 获取孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24116275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java JSONObject get children
提问by Ilkar
i want to create gmaps on my website.
我想在我的网站上创建 gmap。
I found, how to get coordinates.
我发现,如何获得坐标。
{
"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"
}
I want to get:
我想得到:
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
From this Json.
从这个 Json.
I decided to user json-simple
我决定使用 json-simple
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
My code is:
我的代码是:
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
And i can get the first children: "results"
我可以得到第一个孩子:“结果”
String json2 = json.get("results").toString();
json2 display correct body of "results"
json2 显示正确的“结果”正文
But i cannot get "location" children.
但我不能得到“位置”的孩子。
How to do it ?
怎么做 ?
Thanks
谢谢
回答by Woodham
I think you need to cast the call to json.get("results")
to a JSONArray
.
我认为您需要将呼叫转换json.get("results")
为 a JSONArray
。
I.e.
IE
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()
The trick is to look at what type the part of the json you're deserializing is and cast it to the appropriate type.
诀窍是查看您正在反序列化的 json 部分是什么类型并将其转换为适当的类型。