繁体   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