Modify JsonNode with Java Jackson

In the previous lessons, we covered converting a Java Object to JsonNode and vice versa. Here, you will see how to modify JsonNode with the Java Jackson library.

To see where to find Jackson jars, read Introduction to Java JSON.

How to modify JsonNode with Java Jackson?

The JsonNode class is immutable. That means we cannot modify it. For that purpose, we can use the ObjectNode, which is the subclass of the JsonNode.

In this lesson, we will cover adding and removing a field from the JsonNode.

How to add a field to a JsonNode?

Since we can not modify the JsonNode, we first need to cast it to the ObjectNode.
Let’s create an empty JsonNode and add a field to it.

class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    JsonNode jsonNode = objectMapper.createObjectNode();

    ((ObjectNode) jsonNode).put("key1", "value1");

    System.out.println(jsonNode.toPrettyString());
  }
}
Output: { “key1” : “value1” }
 
Now let’s add a field that represents a User object:
 
  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    JsonNode jsonNode = objectMapper.createObjectNode();

    ((ObjectNode) jsonNode).put("key1", "value1");
    ((ObjectNode) jsonNode).set("user", objectMapper.convertValue(new User("Steve", "Paris", "France"), JsonNode.class));

    System.out.println(jsonNode.toPrettyString());
  }
Output: { “key1” : “value1”, “user” : { “name” : “Steve”, “city” : “Paris”, “state” : “France” } }

How to remove a field from JsonNode?

Removing the “user” field from the JsonNode:

class Test {
  
  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    String json = "{\"key1\":\"value1\",\"user\":{\"name\":\"Steve\",\"city\":\"Paris\",\"state\":\"France\"}}";

    JsonNode jsonNode = objectMapper.readTree(json);

    ((ObjectNode) jsonNode).remove("user");

    System.out.println(jsonNode.toPrettyString());
  }
}
Output: { “key1” : “value1” }
 
That was all about how to modify the JsonNode. Proceed to the next lesson to learn how to iterate over JsonNode in Java Jackson.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *