How to modify a JsonNode in Java (Jackson ObjectNode and ArrayNode)
Codemia Knowledge Hub ·
You cannot change a Jackson JsonNode through the JsonNode type itself, because it is treated as immutable. To modify it, check what kind of node it is and cast it to the mutable subclass: ObjectNode for a JSON object (use put, remove) or ArrayNode for a JSON array (use add, set, remove). Then serialize it back with ObjectMapper.writeValueAsString.
- ObjectNode represents a JSON object (key-value pairs).
- ArrayNode represents a JSON array.
Both extend JsonNode and let you add, update and remove fields and values.
Parse the JSON into a JsonNode
readTree parses the string into a JsonNode tree.
Set or update a field with ObjectNode
If the node is a JSON object, cast it to ObjectNode:
Useful ObjectNode methods:
put(String fieldName, String value)adds or updates a field.remove(String fieldName)removes a field.has(String fieldName)checks whether a field exists.
Add or replace array elements with ArrayNode
For a JSON array, cast to ArrayNode:
Useful ArrayNode methods:
add(String value)appends a value.set(int index, String value)replaces the value at a position.remove(int index)removes an element.
ObjectNode and ArrayNode methods side by side
| Operation | ObjectNode Method | ArrayNode Method | Description |
| Add/Update | put(String, String) | add(String) / set(int, String) | Add or modify field/element |
| Remove | remove(String) | remove(int) | Remove field/element |
| Check Existence | has(String) | N/A | Check field existence (only for ObjectNode) |
Write the modified node back to a string
The output includes every change made through the ObjectNode or ArrayNode casts, because they modify the same tree.
Related reading
- How to modify request body before reaching controller in spring boot
- How to negate a method reference predicate
- How to obtain all subsequence combinations of a String in Java, or C etc
- How to obtain JNI interface pointer JNIEnv for asynchronous calls
- How to override application.properties during production in Spring-Boot?
- How to parse a JSON string into JsonNode in Jackson?
- How to parse JSON in Java
- How to pass a function as a parameter in Java?
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.