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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With