How to Setup Jackson in Java Application?
Last Updated :
05 Aug, 2021
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]
Similar Reads
How to Setup GSON For Java Application?
GSON is Google's JSON parser. It is used to parse JSON files and generate JSON files. It has multiple APIs which serialize Java objects to JSON and deserializes JSON files to Java objects. To use GSON in your java application, we first need to install it. To do this, we can either add GSON jar depen
7 min read
How To Build Java Application In Jenkins ?
In the software development lifecycle, building and testing applications are basic steps toward ensure code quality and dependability. Jenkins, an open-source automation server, plays a vital role in automating these cycles, especially for Java applications. Java, being one of the most generally uti
7 min read
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means âNext Generationâ and it is influenced by JUnit and it follows the annotations (@). Â End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via
4 min read
How to Run Spring Boot Application?
Spring Boot is built on the top of Spring and contains all the features of Spring. And it is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and set
8 min read
How to Set Context Path in Spring Boot Application?
The context path is a prefix to the URL path used to identify and differentiate between different context(s). In Spring Boot, by default, the applications are accessed by context path â/â. That means we can access the application directly at http://localhost:PORT/. For example http://localhost:8080/
6 min read
How to Add JAR file to Classpath in Java?
JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be
4 min read
Web Container and Web Application Project Setup in Java
Web container is a web server component that interacts with the Java Servlets. This processes the requests to the requested servlet while checking the required access rights of the URL. Web containerThe functioning is as follows: The web client requests a URL to the web server.The web container in t
2 min read
How to Install Spring Boot Application in Hostinger?
Spring Boot is a popular platform for developing Java-based web applications, known for its robust features and ease of use. Hostinger offers high-quality, affordable hosting that is well-suited for Spring Boot applications. This article will guide you through deploying your Spring Boot application
4 min read
Elasticsearch in Java Applications
Elasticsearch is a distributed, free, and public search and analytics engine, that works with all kinds of data, including numerical, textual, geographic, structured, and unstructured. Elasticsearch is lightweight. Elasticsearch has a total dependence size of only about 300 KB. It is just concerned
3 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to con
3 min read