[英]Java JSONObject get children
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谢谢
I think you need to cast the call to json.get("results")
to a JSONArray
.我认为您需要json.get("results")
的调用转换为JSONArray
。
Ie 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 部分是什么类型并将其转换为适当的类型。
com.google.gson.JsonParser#parse(java.lang.String)
is now deprecated com.google.gson.JsonParser#parse(java.lang.String)
现已弃用
so use com.google.gson.JsonParser#parseString
, it works pretty well所以使用com.google.gson.JsonParser#parseString
,它工作得很好
Kotlin Example:科特林示例:
val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject
Java Example: Java 示例:
JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.