How to Append To and Update a JsonNode in Java


How can we append to or update a JsonNode in Java?

Most read operations are performed on JsonNode, but mutations occur in ObjectNode and ArrayNode.

1. Adding entry to ObjectNode

We can first cast our JsonNode to an ObjectNode, which contains a put() method to append new key-value entries to our node.

ObjectNode o = (ObjectNode) jsonNode;
o.put("key", "value");

2. Adding ArrayNode to ObjectNode

We can append a new ArrayNode to our ObjectNode by casting to an ObjectNode, calling putArray(), and adding elements using add().

ObjectNode o = (ObjectNode) jsonNode;
o.putArray("arrayName").add("value");

3. Adding to an existing ArrayNode

If our JsonNode references an ArrayNode, we can simply cast it to an ArrayNode and call add().

ArrayNode a = (ArrayNode) jsonNode;
a.add("value");