Javatpoint Logo
Javatpoint Logo

Tree Model in Jackson

The tree model is another important concept in Jackson. It is used to get the in-memory representation of the JSON document. ObjectMapper class is used for building the tree of nodes (JsonNode).

There are the following two tree operations:

  • Creating a tree from JSON
  • Traversing tree model

Creating a Tree from JSON

We use ObjectMapper class for creating Tree Model. It provides a pointer for the root node of the tree after reading the JSON. The root node provided by ObjectMapper class allows us to traverse the complete tree.

Syntax of reading data from Model Tree is as follows:

We use the try-catch block to create a tree because it can throw JsonParseException, JsonMappingException, or IOException.

Traversing Tree Model

After creating Tree from JSON, it is required to traverse it for printing the data. At the time of traversing Tree, we get each node and process data using a path relative to the root node. We traverse Tree model in the following way:

Let's take an example to understand how we can create a Tree model from JSON and iterate it to show the data of each node.

TreeModelExample.java

Output:

Tree Model in Jackson

Explanation:

In the above code, first, we take input from the user to create a Java object of Player. After that, we convert the Java object into JSON to make a Tree Model of the Player object. We use the readTree() method of the ObjectMapper class to get the root node. By using this root node, we get values of id, name, and scores node with the help of the path() method of JsonNode. We use an iterator for traversing each element of the scores node. The intValue() and the textvalue() methods are used for reading node value as number or text.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA