How to modify JsonNode in Java?
I need to change a JSON attribute's value in Java, I can get the value properly but I couldn't modify the JSON.
here is the code below
JsonNode blablas = mapper.readTree(parser).get("blablas");
for (JsonNode jsonNode : blablas) {
String elementId = jsonNode.get("element").asText();
String value = jsonNode.get("value").asText();
if (StringUtils.equalsIgnoreCase(elementId, "blabla")) {
if(value != null && value.equals("YES")){
// I need to change the node to NO then save it into the JSON
}
}
}
What is the best way to do this?
JsonNode
is immutable and is intended for parse operation. However, it can be cast into ObjectNode
(and ArrayNode
) that allow mutations:
((ObjectNode)jsonNode).put("value", "NO");
For an array, you can use:
((ObjectNode)jsonNode).putArray("arrayName").add(object.getValue());
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
-
get
the value/array of theJsonNode
- Perform your modification on that value/array
- Proceed to call
put
on the parent.
Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
I think you can just cast to ObjectNode and use put
method. Like this
ObjectNode o = (ObjectNode) jsonNode;
o.put("value", "NO");
The @Sharon-Ben-Asher answer is ok.
But in my case, for an array i have to use:
((ArrayNode) jsonNode).add("value");