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
import java.io.*;
class GFG {
public static void main(String[] args)
{
Employee employee = getEmployee();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(
new File(
"/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json" ),
employee);
String empJson
= mapper.writeValueAsString(employee);
System.out.println(
"The employee object in json format:"
+ empJson);
System.out.println(
"Updating the dept of emp object" );
employee.setDeptName( "Devops" );
System.out.println(
"Deserializing updated emp json " );
Employee updatedEmp = mapper.readValue(
mapper.writeValueAsString(employee),
Employee. class );
System.out.println( "Updated emp object is "
+ updatedEmp.toString());
}
catch (JsonGenerationException e) {
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private static Employee getEmployee()
{
Employee emp = new Employee();
emp.setId( "E010890" );
emp.setName( "James" );
emp.setDeptName( "DBMS" );
emp.setRating( 5 );
emp.setSalary( 1000000.00 );
return emp;
}
}
class Employee {
private String id;
private String name;
private String deptName;
private double salary;
private int rating;
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 .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
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 GFG {
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
try {
InputStream inputStream = new FileInputStream(
"/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json" );
Employee emp = mapper.readValue(inputStream,
Employee. class );
System.out.println(emp.toString());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Employee {
private String id;
private String name;
private String deptName;
private double salary;
private int rating;
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 .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]
Share your thoughts in the comments
Please Login to comment...