简体   繁体   中英

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)

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)

I can have a json response like this: (with a single element)

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

or I can have a json response like this: (with a )

{  "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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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