Jackson Tree Model Example – JsonNode

In this Jackson Tree Model Example, we will learn how to convert Java Object to JSON and vice-versa ( JSON to Java object). Jackson Tree Model creates a tree representation of a JSON similar to DOM Tree. Hence it is possible to traverse through each node. Jackson  provides JsonNode API through we will be accessing the individual node using the node name.The readTree and writeTree methods of the Jackson ObjectMapper is used to read and write JSON tree.
Folder Structure:

    1. Create a new Java Project  JacksonJSONTutorial” and create a package for our src files com.javainterviewpoint
    2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar

if you are running on maven add the below dependency to your pom.xml

 <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-core-asl</artifactId>
   <version>1.9.13</version>
</dependency>
<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.13</version>
</dependency>
  1. Create the Java classes Read_JSON.java and Write_JSON.java under  com.javainterviewpoint folder.

Jackson Tree Model Example

In order to Convert JSON to Java object and Convert Java Object to JSON again. We will be using the below JSON file.

JSON file content(user.json)

{ 
 "name" : "JavaInterviewPoint", 
 "age" : 999, 
 "favoriteSports" : [ "Football", "Cricket", "Tennis","Basket Ball"] 
}

Read JSON using Jackson Tree Model

package com.javainterviewpoint;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class Read_JSON
{
    public static void main(String[] args)
    {
        try
        {
            //Create ObjectMapper object
            ObjectMapper mapper = new ObjectMapper();
            // Reading the json file
            JsonNode rootNode = mapper.
                    readTree(new File("C:\\Jackson\\user.json"));
            
            //Reading individual nodes
            JsonNode nameNode = rootNode.get("name");
            System.out.println("Name : "+nameNode.asText());
            
            JsonNode ageNode = rootNode.get("age");
            System.out.println("Age : "+ageNode.asText());
            
            JsonNode favSportsNode = rootNode.get("favoriteSports");
            System.out.println("Favourite Sports : ");
            for(JsonNode node : favSportsNode)
            {
                System.out.println("        "+node.asText());
            }
            
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
  • The readTree() method of ObjectMapper reads the JSON files and returns JsonNode Type object, save it as the rootNode
JsonNode rootNode = mapper.
             readTree(new File("C:\\Jackson\\user.json"));
  • Read the individual node using the get() on the rootNode object and save as individual node(nameNode, ageNode, favSportsNode).
JsonNode nameNode = rootNode.get("name");
JsonNode ageNode = rootNode.get("age");
JsonNode favSportsNode = rootNode.get("favoriteSports");
  • Use the asText() method to convert the node to String.

Output:

Jackson Tree Model Example - Read JSON

 

 

 

 

Write JSON using Jackson Tree Model

package com.javainterviewpoint;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

public class Write_JSON
{
    public static void main(String[] args)
    {
        try
        {
            //Create a new ObjectMapper object
            ObjectMapper mapper = new ObjectMapper();
            //Get a JsonGenerator object from ObjectMapper
            JsonGenerator jsonGenerator = mapper.getJsonFactory().
                    createJsonGenerator(System.out);
            
            //Create the rootNode
            JsonNode rootNode = mapper.createObjectNode(); 
            //Writing a simple node
            ((ObjectNode) rootNode).put("Name", "JIP");
            ((ObjectNode) rootNode).put("Age", "3333");
            
            //Writing a Array
            ArrayNode arrayNode = ((ObjectNode) rootNode).putArray("Country");
            arrayNode.add("India");
            arrayNode.add("England");
            arrayNode.add("China");
            arrayNode.add("Japan");
            
            mapper.writeTree(jsonGenerator, rootNode);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
  • createJsonGenerator() method of the JsonFactory returns the JsonGenerator object. Pass “System.out” as the parameter to the createJsonGenerator() method to print the output in the console.
JsonGenerator jsonGenerator = mapper.getJsonFactory().
                    createJsonGenerator(System.out);
  • Create the rootNode using the createObjectNode() of the ObjectMapper
JsonNode rootNode = mapper.createObjectNode();
  • Using the put() method add all the individual values.
((ObjectNode) rootNode).put("Name", "JIP");
((ObjectNode) rootNode).put("Age", "3333");
ArrayNode arrayNode = ((ObjectNode) rootNode).putArray("Country");
arrayNode.add("India");
arrayNode.add("England");
arrayNode.add("China");
arrayNode.add("Japan");
  • Finally, using the writeTree() write the JSON. The writeTree() method takes two parameters jsonGenerator, rootNode.
mapper.writeTree(jsonGenerator, rootNode);

Output:

{"Name":"JIP","Age":"3333","Country":["India","England","China","Japan"]}

Leave a Reply

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