简体   繁体   English

如何在Java中获取深度嵌套的JSON对象

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

I have a JSON string where i want to get the value of one field which is nested in multiple objects. 我有一个JSON字符串,我想在其中获取嵌套在多个对象中的一个字段的值。 How can I get that field in a nice and performant way? 我怎样才能以一种出色而高效的方式获得该领域? Here's the code I tried so far. 这是我到目前为止尝试过的代码。 It's working, but it's quite lengthy code. 它正在工作,但是代码很长。 I'm looking for a better solution. 我正在寻找更好的解决方案。

Json Response 杰森回应

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

lengthy code : 冗长的代码

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

The result is ruleId = Abs 结果是ruleId = Abs

is there a good alternative for fetching the ruleId from the nested json object (something like response.response.match.matches.matchesSchema.rules.ruleId ) 从嵌套的json对象中获取ruleId是否有很好的选择(如response.response.match.matches.matchesSchema.rules.ruleId

You can use Jackson's JsonNode with JsonPath to get ruleId as follows: 您可以将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()

It's also null -safe and returns a MissingNode object on a null node that returns an empty string when you do a .asText() 它也是null并在执行.asText()时返回空节点的空节点上返回MissingNode对象。

It's super easy with JsonPath . 使用JsonPath超级简单。

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

Or if you read the path multiple times, it's better to pre-compile JsonPath expression 或者,如果您多次读取路径,则最好预先编译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