mstfdz mstfdz - 1 year ago 303
Java Question

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 ?

Thanks in advance.

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download