Explain Codes LogoExplain Codes Logo

How to modify JsonNode in Java?

java
json-parsing
object-mapping
json-pointer
Alex KataevbyAlex Kataev·Feb 19, 2025
TLDR

Modifying a JsonNode? Jackson is your friend. Use the shiny ObjectMapper, and tactfully call put or replace on an ObjectNode, the alterable cousin of JsonNode.

Code snippet your eyes want to see:

ObjectMapper mapper = new ObjectMapper(); ObjectNode node = (ObjectNode) mapper.readTree(jsonString); // Fetch a mutable instance node.put("key", "updatedValue"); // Apply changes (like a true hacker) String updatedJson = mapper.writeValueAsString(node); // Serialize!

Embracing Immutable

JsonNode being immutable, is like a fortress guarding your data. To modify, casting to ObjectNode or ArrayNode is the key. They are JsonNode on the inside but behave like mutable chameleons.

Unraveling Nested structures

If nested JSON is throwing curveballs, you recursively fetch the ObjectNode instances representing the levels you want to tweak. Casting and type checks: are your trusty sidekicks:

ObjectNode parentNode = (ObjectNode) jsonNode.path("parent"); // Obtain parent ObjectNode childNode = (ObjectNode) parentNode.path("child"); // Obtain child childNode.put("field", "newValue"); // We have the power now, muahaha

Remember, always verify the node type before throwing your type-casting spells:

// No JsonNode was harmed in the execution of this statement. if (jsonNode.isObject()) { // Cast away }

Mastering arrays

JSON arrays are quirky. They are managed via ArrayNode which has methods to add and remove elements:

ArrayNode arrayNode = (ArrayNode) jsonNode.path("arrayField"); // Behold, the array node arrayNode.add("newElement"); // Just squeezing in a new element

Note: JSON arrays love order. For replacing an element, set() sneaks in to help:

arrayNode.set(index, newValue); // It's not scalpel precision, but it'll do

Dealing with nulls

Nulls, the nemesis. While handling JsonNode, brace yourself for null. Null checks are essential defensive maneuvers:

JsonNode valueNode = someNode.get("key"); // My precious...null? if (valueNode != null && !valueNode.isNull()) { // Rejoice, we have a value }

Field names: Dynamic beats static

Hardcoded field names, a "no-no". For the last field in a JSON, use JsonPointer.last() for a sniper shot.

Swapping nodes

When subtle tweaks won't cut it, entire node replacement comes to the rescue. Node replacement is a mighty hammer Jackson packs:

ObjectNode newSubtree = mapper.createObjectNode(); // Crafting a new subtree newSubtree.put("new", "structure"); // Adding some foliage perhaps node.set("subtree", newSubtree); // Bazinga!

Journey with JsonPointer

Navigating a JSON jungle? JsonPointer expressions show the path. /family/mother is your GPS to find the mother node:

JsonNode mother = rootNode.at("/family/mother"); // Look mom, I found you!

Validation? Sure! Verify structure before any change.

ObjectMapper: The Jack of all trades

The ObjectMapper class, a class to rule them all! Deserialize, merge JSON, or convert data formats. It's a walk in the park.

When legacy strikes

Legacy systems ain't perfect. They hit you with inconsistent JSON. Flexibility and exception handling save the day.