Jackson 2 JSON Parser – Convert JSON to/from Java Object

In this Jackson 2 JSON Parser example we will learn how to Convert JSON to Java object and Convert Java Object to JSON again using Jackson 2 API.

Folder Structure:

Jackson 2 JSON Parser

    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.

commons-io-2.5.jar
jackson-databind.2.8.4.jar

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

 <dependencies>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.8.4</version>
 </dependency>
 <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
  </dependency>
 </dependencies>
  1. Create the Java classes JSONReader.java, JSONWriter.java and StudentDetails.java under  com.javainterviewpoint folder.

Jackson 2 JSON Parser

To Convert JSON to Java object and Convert Java Object to JSON again. We will be using this JSON file.

JSON file content(StudentDetails.json)

{
   "id":999,
   "name":"JavaInterviewPoint",
   "department":"ComputerScience",
   "favoriteSports":["Cricket","Tennis","Football"]
}

StudentDetails.java

A simple POJO, for holding the details of the Student.

package com.javainterviewpoint;

import java.util.List;

public class StudentDetails
{
    private int id;
    private String name;
    private String department;
    private List favoriteSports;

    public StudentDetails()
    {}

    public StudentDetails(int id, String name, String department,
            List favoriteSports)
    {
        this.id = id;
        this.name = name;
        this.department = department;
        this.favoriteSports = favoriteSports;
    }

    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getDepartment()
    {
        return department;
    }
    public void setDepartment(String department)
    {
        this.department = department;
    }
    public List getFavoriteSports()
    {
        return favoriteSports;
    }
    public void setFavoriteSports(List favoriteSports)
    {
        this.favoriteSports = favoriteSports;
    }
}

Convert JSON to Java object

package com.javainterviewpoint;

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

import org.apache.commons.io.FileUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONReader 
{
    public static void main(String[] args)
    {
        String data="";
        //Create a new ObjectMapper, for mapping data to POJO
        ObjectMapper mapper = new ObjectMapper();
        
        try
        {
            //Read the StudentDetails.json
            data = FileUtils.readFileToString(new File("c:\\StudentDetails.json"));
            //Read and map data to studentDetails object
            StudentDetails studentDetails = mapper.readValue(data, StudentDetails.class);
            //Print the studentdetails
            System.out.println("*** StudentDetails Details ***");
            System.out.println("Student Name        : "+studentDetails.getName());
            System.out.println("Student Id          : "+studentDetails.getId());
            System.out.println("Student Department  : "+studentDetails.getDepartment());
            System.out.println("Favourite Sports : ");
            for(String fav : studentDetails.getFavoriteSports())
            {
                System.out.print(fav +" | ");
            }
        } catch (JsonParseException e)
        {
            e.printStackTrace();
        } catch (JsonMappingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
ObjectMapper mapper = new ObjectMapper();
  • Using the apache commons.io, read the “StudentDetails.json” file. You can also read the file with any Java File Reader such as BufferedReader
data = FileUtils.readFileToString(new File("c:\\StudentDetails.json"));
  • The readValue() method of the ObjectMapper class converts the JSON String into Java Object and maps it to the POJO. It takes two parameters data (JSON String) and the POJO class(StudentDetails.class)
StudentDetails studentDetails = mapper.readValue(data, StudentDetails.class);
  • Finally, print the Student details
 System.out.println("*** StudentDetails Details ***");
 System.out.println("Student Name        : "+studentDetails.getName());
 System.out.println("Student Id          : "+studentDetails.getId());
 System.out.println("Student Department  : "+studentDetails.getDepartment());
 System.out.println("Favourite Sports : ");
 for(String fav : studentDetails.getFavoriteSports())
 {
      System.out.print(fav +" | ");
 }

Output : 

*** StudentDetails Details ***
Student Name        : JavaInterviewPoint
Student Id          : 999
Student Department  : ComputerScience
Favourite Sports : 
Cricket | Tennis | Football

 

Convert Java Object to JSON

package com.javainterviewpoint;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONWriter 
{
    public static void main(String[] args)
    {
        try 
        {
            //Create a new StudentDetails object
            StudentDetails studentDetails = new StudentDetails();
            //set value to its properties
            studentDetails.setName("JavaInterviewPoint");
            studentDetails.setId(1);
            studentDetails.setDepartment("Science");
            
            List favoriteSports = new ArrayList();
            favoriteSports.add("Cricket");
            favoriteSports.add("Tennis");
            favoriteSports.add("Football");
                        
            studentDetails.setFavoriteSports(favoriteSports);
            //Create a new ObjectMapper, for mapping data to POJO
            ObjectMapper mapper = new ObjectMapper();
            //Set prettyprint option
            mapper.writerWithDefaultPrettyPrinter();
            //Write the studentDetails data into StudentDetails.json
            mapper.writeValue(new File("c://StudentDetails.json"), studentDetails);
            System.out.println("JSON Write successful!!");
            
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
  • Create a new Object for the StudentDetails class
StudentDetails studentDetails = new StudentDetails();
  • Set value to the properties of StudentDetails
StudentDetails studentDetails = new StudentDetails();
studentDetails.setName("JavaInterviewPoint");
studentDetails.setId(1);
studentDetails.setDepartment("Science");
  • Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
ObjectMapper mapper = new ObjectMapper();
  • Using the writeValue() method of the ObjectMapper class, write the studentDetails object into StudentDetails.json.
mapper.writeValue(new File("c://StudentDetails.json"), studentDetails);

Output :

{
 "id":1,
 "name":"JavaInterviewPoint",
 "department":"Science",
 "favoriteSports":["Cricket","Tennis","Football"]
}

Leave a Reply

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