简体   繁体   English

如何检查 JsonNode 是 Java 中的单个元素还是数组?

[英]How to check if a JsonNode is a single element or an Array in Java?

I am traversing a json response with JsonNode (com.fasterxml.jackson.databind.JsonNode)我正在使用 JsonNode (com.fasterxml.jackson.databind.JsonNode) 遍历 json 响应

How can I check if a given JsonNode is a single element or an Array?, because I need to traverse it deeper, and update some values (for example, the name value)如何检查给定的 JsonNode 是单个元素还是数组?,因为我需要更深入地遍历它,并更新一些值(例如,名称值)

I can have a json response like this: (with a single element)我可以有这样的 json 响应:(带有单个元素)

{  person: {
      name: "name1",
      address: "address1"
   } 
}

or I can have a json response like this: (with a )或者我可以有这样的 json 响应:(带有 )

{  "person": [ 
       {
         "name": "name1",
         "address": "address1"
       }, 
       {
         "name": "name2",
         "address": "address2"
       }
   ]
}

For an single element, I have this code:对于单个元素,我有以下代码:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonString);
JsonNode personNode = root.findPath("person");
if(!personRootNode.isMissingNode()) 
   ((ObjectNode)nameNode).put("name","UPDATED NAME");

And, for an array element, I have this code而且,对于数组元素,我有这个代码

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonString);
JsonNode personNode = root.findPath("person");
if(!personNode .isMissingNode()) 
   for(JsonNode node: personRootNode){
      if(!node.isMissingNode()) {
         ((ObjectNode)node).put("name","UPDATED NAME");
      }
   }

I want to mix the logic in a single place, because the unique difference is the for loop我想在一个地方混合逻辑,因为唯一的区别是 for 循环

I can wrap the replace logic in a function/method.我可以将替换逻辑包装在函数/方法中。 But how do I check if the current node is an element or an array?但是如何检查当前节点是元素还是数组?

You can call isArray() function on JsonNode object.您可以在 JsonNode 对象上调用 isArray() 函数。 For example :例如 :

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(s2);
JsonNode personNode = root.findPath("person");
if(personNode.isArray()) {
///array found
} else {
// non-array element
}

use the below method.使用下面的方法。 Enter the JSONObject to check and node name.(used the org.json.JSONObject)输入要检查的 JSONObject 和节点名称。(使用 org.json.JSONObject)

private void checkNodeStatus(JSONObject jsonObject, String node) {
    if (jsonObject.optJSONArray(node) != null) {
    } else if (jsonObject.optString(node) != null) {
        JSONArray array = new JSONArray();
        array.put(jsonObject.getJSONObject(node));
        jsonObject = jsonObject.put(node, array);
    } else {
        System.out.println("error in checkNodeStatus > node : " + node);
    }
}

if It is a JSONObject, It converts to JSONArray.如果是 JSONObject,则转换为 JSONArray。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM