Jackson
Java
JsonNode
JSON
Object Mapping

Convert a Java object to JsonNode in Jackson

Codemia Knowledge Hub ·

Use ObjectMapper.valueToTree(Object). It converts a Java object directly into Jackson's JsonNode, the tree model that represents a JSON structure, without going through a JSON string. Jackson is one of the most popular JSON libraries for Java, and its ObjectMapper handles conversion between Java objects, JSON text and the tree model.

What JsonNode is

JsonNode is part of Jackson's Tree Model, which represents JSON as a tree of node objects. It is an abstract class with concrete implementations such as ObjectNode and ArrayNode. The tree model is useful when the JSON structure is unknown, or when you prefer to manipulate JSON as a tree.

Converting an object with valueToTree

java
1import com.fasterxml.jackson.databind.JsonNode;
2import com.fasterxml.jackson.databind.ObjectMapper;
3
4public class Main {
5    public static void main(String[] args) {
6        ObjectMapper objectMapper = new ObjectMapper();
7        User user = new User("John", "Doe", 30);
8
9        try {
10            JsonNode jsonNode = objectMapper.valueToTree(user);
11            System.out.println(jsonNode.toPrettyString());
12        } catch (Exception e) {
13            e.printStackTrace();
14        }
15    }
16}
17
18class User {
19    private String firstName;
20    private String lastName;
21    private int age;
22
23    public User(String firstName, String lastName, int age) {
24        this.firstName = firstName;
25        this.lastName = lastName;
26        this.age = age;
27    }
28
29    // Getters and setters...
30}
  • ObjectMapper: Jackson's core class. valueToTree(Object fromValue) converts an object to a JsonNode.
  • JsonNode: a node in a JSON tree.

Because JsonNode does not need a schema, it handles varying JSON structures easily, and you can traverse and manipulate the data like any tree.

Reading fields from the JsonNode

Once the object is a JsonNode, read values with get() and convert them with methods such as asText() and asInt():

java
1JsonNode rootNode = objectMapper.valueToTree(user);
2String firstName = rootNode.get("firstName").asText();
3int age = rootNode.get("age").asInt();
4
5System.out.println("First Name: " + firstName);
6System.out.println("Age: " + age);

Adding and removing fields

To add or remove fields dynamically, cast the JsonNode from the first example to ObjectNode, the concrete type for JSON objects:

java
ObjectNode objectNode = (ObjectNode) jsonNode;
objectNode.put("email", "[email protected]"); // Adds a new field
objectNode.remove("age"); // Removes the age field

Serializing the JsonNode back to a string

To turn the tree back into JSON text, pass it to writeValueAsString:

java
String jsonString = objectMapper.writeValueAsString(jsonNode);
System.out.println(jsonString);

Quick reference

FeatureDescriptionCode Example
Basic ConversionConverts a Java object to JsonNodeobjectMapper.valueToTree(user)
Accessing DataAccess and read values from JsonNoderootNode.get("firstName").asText()
Modifying JsonNodeAdding/removing fieldsobjectNode.put("email", ...); objectNode.remove("age")
Serializing JsonNodeConvert JsonNode back to JSON stringobjectMapper.writeValueAsString(jsonNode)

The tree model gives you flexibility with complex or unpredictable JSON, whether you are serializing, deserializing or modifying data.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms