Java Jackson @JsonDeserialize

1. Overview

Jackson is a highly efficient Java library used for converting Java objects into JSON representations and vice-versa. A crucial part of this process, especially for complex deserializations, involves the @JsonDeserialize annotation. Using the context of an Employee Management System, this post will explore its applications.

@JsonDeserialize Annotation Overview

The @JsonDeserialize annotation is employed in Jackson to specify custom deserialization for Java objects. This can be especially useful when the structure of the incoming JSON doesn't match the Java object's structure or when some custom processing is required during deserialization.

2. Development Steps

1. Set up a new Maven project.

2. Include the required Jackson dependencies.

3. Design an Employee class showcasing the @JsonDeserialize usage.

4. Create a main class for testing and demonstration.

5. Deserialize a sample JSON into an Employee object.

3. Create a Maven Project

There are different ways to create a simple Maven project:

Create a Simple Maven Project using the Command Line Interface

Create a Simple Maven Project using  Eclipse IDE

Create a Simple Maven Project using  IntelliJ IDEA

4. Maven Dependencies

Open the pom.xml file, and add the following Jackson data binding dependency:

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

5. Code Program

Consider the following classes for the Employee Management System:
// CustomEmployeeDeserializer.java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
public class CustomEmployeeDeserializer extends JsonDeserializer<Employee> {
    @Override
    public Employee deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String[] parts = p.getText().split(",");
        Employee emp = new Employee();
        emp.setId(Integer.parseInt(parts[0]));
        emp.setName(parts[1]);
        return emp;
    }
}

// Employee.java
public class Employee {
    private int id;
    private String name;
    // Standard getters and setters omitted for brevity...
    @JsonDeserialize(using = CustomEmployeeDeserializer.class)
    public void setNameAndId(String combined) {
        // This method won't be used, but the annotation will trigger the custom deserializer
    }
}

// MainDemo.java
import com.fasterxml.jackson.databind.ObjectMapper;
public class MainDemo {
    public static void main(String[] args) {
        String json = "\"1,John Doe\"";
        ObjectMapper mapper = new ObjectMapper();
        try {
            Employee employee = mapper.readValue(json, Employee.class);
            System.out.println("Employee ID: " + employee.getId());
            System.out.println("Employee Name: " + employee.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Employee ID: 1
Employee Name: John Doe

Code Explanation:

Here's a twist: the JSON contains the employee's ID and name as a single string, separated by a comma. To address this, the CustomEmployeeDeserializer class has been implemented. 

When Jackson comes across the @JsonDeserialize annotation in the Employee class, it utilizes this custom deserializer to convert the single string into separate id and name attributes of the Employee object.

6. Conclusion

Jackson's @JsonDeserialize annotation furnishes a powerful toolset for handling unconventional JSON formats or executing custom deserialization logic. By decoupling the deserialization logic and integrating it with Jackson's framework, developers can maintain clean domain models even when dealing with intricate JSON structures.

Comments