簡體   English   中英

Java JSONObject 獲取孩子

[英]Java JSONObject get children

我想在我的網站上創建 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);

我可以得到第一個孩子:“結果”

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

json2 顯示正確的“結果”正文

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

怎么做 ?

謝謝

我認為您需要json.get("results")的調用轉換為JSONArray

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

訣竅是查看您正在反序列化的 json 部分是什么類型並將其轉換為適當的類型。

關於這個鏈接

com.google.gson.JsonParser#parse(java.lang.String)現已棄用

所以使用com.google.gson.JsonParser#parseString ,它工作得很好

科特林示例:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java 示例:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM