簡體   English   中英

如何在Java中獲取深度嵌套的JSON對象

[英]How to get deeply nested JSON object in Java

我有一個JSON字符串,我想在其中獲取嵌套在多個對象中的一個字段的值。 我怎樣才能以一種出色而高效的方式獲得該領域? 這是我到目前為止嘗試過的代碼。 它正在工作,但是代碼很長。 我正在尋找更好的解決方案。

傑森回應

{  
   "status":"success",
   "response":{  
      "setId":1,
      "response":{  
         "match":{  
            "matches":{  
               "matchesSchema":{  
                  "rules":[  
                     {  
                        "ruleId":"Abs"
                     }
                  ]
               }
            }
         }
      }
   }

冗長的代碼

JsonParser jp=new JsonParser();
Object obj = jp.parse(JSONString); 
JSONObject jsonObject =(JSONObject) (obj);
JSONObject get1 = jsonObject.getJSONObject("response");
JSONObject get2 = get1 .getJSONObject("response");
JSONObject get3 = get2 .getJSONObject("match");
JSONObject get4 = get3 .getJSONObject("matches");
JSONObject get5 = get4 .getJSONObject("matchesSchema");
JSONObject get6 = get5 .getJSONObject("rules");
JSONArray result = get6 .getJSONArray("rules");
JSONObject result1 = result.getJSONObject(0);
String lat = result1 .getString("rule");

結果是ruleId = Abs

從嵌套的json對象中獲取ruleId是否有很好的選擇(如response.response.match.matches.matchesSchema.rules.ruleId

您可以將Jackson的JsonNode與JsonPath JsonNode使用,以獲取ruleId ,如下所示:

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj = mapper.readTree(JSONString);
String lat = jsonObj.at("/response/response/match/matches/matchesSchema/rules/0/ruleId").asText()

它也是null並在執行.asText()時返回空節點的空節點上返回MissingNode對象。

使用JsonPath超級簡單。

String ruleId = JsonPath.read(jsonString, "$.response.response.match.matches.matchesSchema.rules[0].ruleId");

或者,如果您多次讀取路徑,則最好預先編譯JsonPath表達式

JsonPath ruleIdPath = JsonPath.compile("$.response.response.match.matches.matchesSchema.rules[0].ruleId");
String ruleId = ruleIdPath.read(json);

暫無
暫無

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

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