Java JSONObject 获取 child

标签 java json

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

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

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

<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);

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

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

关于Java JSONObject 获取 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116275/

相关文章:

json - Ambari群集+为了将蓝图json文件上传到ambari群集,正确的语法是什么

java - 当传递的参数是不同对象的数组时,如何在方法中声明参数类型?

java - 将 Akka 代理与更改相同数据的遗留代码混合

java - Hibernate 二级缓存使用 redis 用于多个容器

java - Dom4j获取单节点文本值

jquery - 如何通过表单元素传递 json

javascript - 为什么在这种情况下 jquery 不调用成功处理程序?

ios - 使用 NSJSONSerialization 反序列化压缩的 JSON 文件

java - 向某些第三方 Web 应用程序发送登录请求

ios - 从IOS中的json响应中提取错误代码