Tree Model in JacksonThe 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 JSONWe 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 ModelAfter 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: 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.
Next TopicJackson Streaming API
|