• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Jackson Tree Model Example – JsonNode

October 19, 2016 by javainterviewpoint Leave a Comment

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.

Other Posts which you may like …

  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

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"]}

Filed Under: Core Java, Java, JSON Tagged With: Jackson Tree Model, Jackson Tree Model Example, JsonNode

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·