Open In App

How to Setup Jackson in Java Application?

Last Updated : 05 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

JSON(Javascript Object Notation) is the most popular format for the exchange of data in the world of web applications. The browsers can easily parse json requests and convert them to javascript objects.  The servers parse json requests, process them, and generates a new json response. JSON is self-describing and easy to understand. The process of converting java objects to json is called serialization and the process of converting json to java objects is called deserialization.

Consider a sample illustration below to get to know the file structure of json as shown below:

Illustration:

We have a Student class with attributes like id, name, address, city, hobby. Let’s understand how the corresponding json file looks as follows:

{"id":"S1122","name":"Jane","address":"XYZ Street","city":"Mumbai","hobby":"Badminton, Dancing"}

JSON data is written as a name/value pair where the name is the attribute/property name and value is the value for that attribute.

Now let us do discuss out Jackson JSON library before proceeding to set up Jackson for any java application.

  • For java applications, it is very difficult to work with Json strings. So in java applications we need a json parser which parses Json files and converts them to java objects.
  • Jackson is one such  Java Json library used for parsing and generating Json files. It has built in Object Mapper class which parses json files and deserializes it to custom java objects. It helps in generating json from java objects.
  • Jackson also has a Jackson Json Parser and Jackson Json Generator which parses and generates json one token at a time.

Setup:-

To use Jackson library in our application, we need to add the below dependencies in the pom.xml file of our maven project.

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.9.6</version>
</dependency>

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-annotations</artifactId>
   <version>2.9.6</version>
</dependency>

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.6</version>
</dependency>

On adding this dependency in pom.xml, the following jar files get added in Maven dependencies folder in eclipse:

  • jackson-core-2.9.6.jar
  • jackson-annotations-2.9.6.jar
  • jackson-databind-2.9.6.jar

Note: If we are not using maven project, then we need to download and add these jar files in our classpath.

Implementation: Let’s understand how the Jackson library parses json files and generates them.

Let’s consider Employee class with attributes like name, id, deptName, salary, rating. We use Jackson library to generate a json file from the Employee object. We update one of its attributes – deptName. We serialize the employee object to a json file and then deserialize it back to an employee object with the updated value for the deptName attribute.

Example 1

Java




//  Java Program to Illustrate Setting Up of Jackson by
//  parsing Jackson library json files and
//  generating the same
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an employee object with it's attributes
        // set
        Employee employee = getEmployee();
        ObjectMapper mapper = new ObjectMapper();
 
        // Try block to check for exceptions
        try {
 
            // Serializes emp object to a file employee.json
            mapper.writeValue(
                new File(
                    "/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json"),
                employee);
 
            // Deserializes emp object in json string format
            String empJson
                = mapper.writeValueAsString(employee);
            System.out.println(
                "The employee object in json format:"
                + empJson);
            System.out.println(
                "Updating the dept of emp object");
 
            // Update deptName attribute of emp object
            employee.setDeptName("Devops");
            System.out.println(
                "Deserializing updated emp json ");
 
            // Reading from updated json and deserializes it
            // to emp object
            Employee updatedEmp = mapper.readValue(
                mapper.writeValueAsString(employee),
                Employee.class);
 
            // Print and display the updated employee object
            System.out.println("Updated emp object is "
                               + updatedEmp.toString());
        }
  
        // Catch block to handle exceptions
 
        // Catch block 1
        // Handling JsonGenerationException
        catch (JsonGenerationException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Catch block 2
        // Handling JsonmappingException
        catch (JsonMappingException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Catch block 3
        // handling generic I/O exceptions
        catch (IOException e) {
 
            // Display the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
 
    // Method 2
    // To get the employees
    private static Employee getEmployee()
    {
        // Creating an object of Employee class
        Employee emp = new Employee();
        emp.setId("E010890");
        emp.setName("James");
        emp.setDeptName("DBMS");
        emp.setRating(5);
        emp.setSalary(1000000.00);
 
        // Returning the employee
        return emp;
    }
}
 
// Class 2
// Helper class
class Employee {
 
    // Member variables of this class
    private String id;
    private String name;
    private String deptName;
    private double salary;
    private int rating;
 
    // Member methods of this class
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDeptName() { return deptName; }
    public void setDeptName(String deptName)
    {
        // This keyword refers to current instance
        this.deptName = deptName;
    }
 
    public double getSalary() { return salary; }
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
    public int getRating() { return rating; }
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", deptName=" + deptName + ", salary="
            + salary + ", rating=" + rating + "]";
    }
}


Output:

The employee object in json format:{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}
Updating the dept of emp object
Deserializing updated emp json 
Updated emp object is Employee [id=E010890, name=James, deptName=Devops, salary=1000000.0, rating=5]

In the src/main/resources folder, employee.json is created.

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

Now let us move onto the next example where we will be using Jackson to read an object from an InputStream using Object Mapper and deserialize it into a java object.

Note: Here we will be having a file named employee.json in src/main/resources folder

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

We will be using ObjectMapper class readValue() method to read a file.

ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream("file-path"); 
Employee emp = mapper.readValue(inputStream, Employee.class);

Example

Java




//  Java Program to Illustrate Setting Up of Jackson by
//  Reading an object from an InputStream
// Using Object Mapper & deserializing to object
 
// Importing required classes
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object mapper instance
        ObjectMapper mapper = new ObjectMapper();
 
        // Try block to check for exceptions
        try {
 
            // input stream points to a json file in
            // src/main/resources folder
            InputStream inputStream = new FileInputStream(
                "/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json");
 
            // Deserializes from json file to employee
            // object
            Employee emp = mapper.readValue(inputStream,
                                            Employee.class);
            System.out.println(emp.toString());
        }
 
        // Catch blocks to handle the exceptions
 
        // Catch block 1
        // Handling FileNotFoundException
        catch (FileNotFoundException e) {
 
            // Displaying the exception along with line
            // number using printStackTrace()
            e.printStackTrace();
        }
 
        // Catch block 2
        catch (JsonParseException e) {
 
            // Displaying the exception along with line
            // number using printStackTrace()
            e.printStackTrace();
        }
 
        // Catch block 3
        catch (JsonMappingException e) {
            e.printStackTrace();
        }
 
        // Catch block 4
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}
 
// Class 2
// Helper class
class Employee {
 
    // Member variables of this class
    private String id;
    private String name;
    private String deptName;
    private double salary;
    private int rating;
 
    // Member methods of this class
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDeptName() { return deptName; }
    public void setDeptName(String deptName)
    {
        // This keyword refers to current object itself
        this.deptName = deptName;
    }
 
    public double getSalary() { return salary; }
 
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
 
    public int getRating() { return rating; }
 
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", deptName=" + deptName + ", salary="
            + salary + ", rating=" + rating + "]";
    }
}


Output:

Employee [id=E010890, name=James, deptName=DBMS, salary=1000000.0, rating=5]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads