In this article, you delve into the world of JSON serialization and deserialization using the powerful Jackson JSON library. Whether you’re a seasoned developer or just starting your journey in Java programming, this guide will walk you through the process of setting up a Maven project in the Eclipse IDE, creating a simple “Employee” class, and demonstrating how to harness the capabilities of Jackson to effortlessly serialize and deserialize Java objects.
In today’s interconnected world, efficient data exchange between different systems lies at the heart of many software applications. This is where JSON (JavaScript Object Notation) steps in, offering a lightweight and human-readable format for transmitting data.
Table of Contents
JSON Serialization and Deserialization
JSON (JavaScript Object Notation) is a lightweight data interchange format. Serialization is the process of converting Java objects into JSON format, while deserialization is the process of converting JSON back into Java objects. These processes are crucial for data exchange between different systems.
Step by step creating an Example in Eclipse IDE
Creating the Maven Project:
To start, setting up a Maven project in Eclipse follow the below steps:
- Open Eclipse.
- Click on “File” > “New” > “Other…”
- Select “Maven Project” and click “Next.”
- Choose an appropriate workspace location and select “Create a simple project” (skip archetype selection).
- Enter a “Group ID” and “Artifact ID” (e.g., “com.javacodepoint” and “JacksonJSONMavenApp”).
- Click “Finish.”
Once you click on Finish, the maven project will be created, and the structure of the maven project looks like the below image:
Adding Jackson dependencies to the project:
Once the project is set up, open the pom.xml
file and add the below Jackson dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
Now, the complete pom.xml looks as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javacodepoint</groupId>
<artifactId>JacksonJSONMavenApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</dependencies>
</project>
See the complete environment setup of Jackson Library in Eclipse for the Maven project, here.
Defining the Employee Class:
Create an Employee
class with attributes like id, name, and department. First of all, create a package under src/main/java. eg- “com.javacodepoint” then create the below Employee class under created package:
package com.javacodepoint;
public class Employee {
private int id;
private String name;
private String department;
// getters, and setters method
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;
}
}
JSON Serialization:
To serialize an Employee
object to JSON, use the following code:
package com.javacodepoint;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SerializationExample {
public static void main(String[] args) throws Exception {
Employee employee = new Employee();
employee.setId(1);
employee.setName("John Doe");
employee.setDepartment("IT");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(employee);
System.out.println(json);
}
}
OUTPUT:
{“id”:1,”name”:”John Doe”,”department”:”IT”}
JSON Deserialization:
package com.javacodepoint;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationExample {
public static void main(String[] args) throws Exception {
String json = "{\"id\":1,\"name\":\"John Doe\",\"department\":\"IT\"}";
ObjectMapper objectMapper = new ObjectMapper();
Employee employee = objectMapper.readValue(json, Employee.class);
System.out.println("Employee ID: " + employee.getId());
System.out.println("Employee Name: " + employee.getName());
System.out.println("Employee Department: " + employee.getDepartment());
}
}
OUTPUT:
Employee ID: 1
Employee Name: John Doe
Employee Department: IT
Handling Complex Objects:
In scenarios where your Java class contains complex objects or relationships, Jackson provides seamless support for their serialization and deserialization. Suppose we enhance our Employee
class to include a Address
object:
package com.javacodepoint;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Employee {
private int id;
private String name;
private String department;
private Address address; // New complex object
// Constructors, getters, and setters
}
class Address {
private String street;
private String city;
private String country;
// Constructors, getters, and setters
}
Jackson handles this naturally during serialization and deserialization. If the Address
class has Jackson annotations (if needed), the entire object hierarchy will be correctly processed.
Customizing Serialization and Deserialization:
Jackson offers a variety of annotations and features to customize the serialization and deserialization process according to your requirements.
For example, let’s say you want to exclude the department
field from serialization:
package com.javacodepoint;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Employee {
private int id;
private String name;
@JsonIgnore
private String department; // This field will be excluded from serialization
// Constructors, getters, and setters
}
Similarly, you can use @JsonProperty
to customize the names of serialized fields:
package com.javacodepoint;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Employee {
@JsonProperty("empId")
private int id;
@JsonProperty("empName")
private String name;
private String department;
// Constructors, getters, and setters
}
For more advanced customization, such as creating custom serializers and deserializers, you can implement JsonSerializer
and JsonDeserializer
interfaces.
Error Handling and Exception Management:
While performing deserialization, it’s essential to handle potential errors gracefully. Jackson provides exception classes like JsonParseException
and JsonMappingException
that can occur during the process. To ensure your application remains stable, enclose your deserialization code in a try-catch block:
package com.javacodepoint;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationExample {
public static void main(String[] args) {
String json = "{\"id\":1,\"name\":\"John Doe\",\"department\":\"IT\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
Employee employee = objectMapper.readValue(json, Employee.class);
System.out.println("Employee Name: " + employee.getName());
} catch (JsonProcessingException e) {
System.out.println("Error during deserialization: " + e.getMessage());
}
}
}
OUTPUT:
Error during deserialization: Unrecognized field “id” (class com.javacodepoint.Employee), not marked as ignorable (2 known properties: “empId”, “empName”])
at [Source: (String)”{“id”:1,”name”:”John Doe”,”department”:”IT”}”; line: 1, column: 8] (through reference chain: com.javacodepoint.Employee[“id”])
By catching exceptions, you prevent unexpected crashes and gain insight into what went wrong during the deserialization process. Remember to handle exceptions as per your application’s requirements.
These aspects—handling complex objects, customization options, and proper error management—augment your understanding of Jackson’s capabilities in achieving efficient and reliable JSON processing in Java.
Conclusion
Understanding JSON serialization and deserialization using the Jackson library is essential for effective data communication in Java applications. By following this guide, you’ve learned how to serialize and deserialize Java objects, customize the process, handle errors, and test your application.
References:
Jackson Documentation