Serialization: How to Create JSON Payload from Java Object Using Jackson API

Serialization is the process of converting a Java object into a format that can be easily transmitted or stored, such as JSON. In modern applications, JSON is a widely used data format for APIs, making serialization a crucial skill for developers. In this blog, we will explore how to use the Jackson API to serialize a Java object into a JSON payload.

What is Jackson API?

Jackson is a popular library for working with JSON in Java. It offers powerful features for serializing and deserializing Java objects to and from JSON. Jackson is part of the FasterXML library family and provides a high-performance solution for JSON handling.

The key components of the Jackson library are:

  • ObjectMapper: A central class for JSON processing.
  • Annotations: For configuring JSON serialization/deserialization behavior.
  • Modules: Extend the functionality for custom needs.

Step-by-Step Guide to Serialize Java Objects into JSON

Step 1: Add Jackson Dependency to Your Project

If you’re using Maven, add the following dependency to your pom.xml:

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.15.2</version>

</dependency>

Step 2: Create a Java Object

Let’s define a simple Java class:

public class Employee {

    private int id;

    private String name;

    private String department;

    private double salary;


    // Constructors

    public Employee(int id, String name, String department, double salary) {

        this.id = id;

        this.name = name;

        this.department = department;

        this.salary = salary;

    }


    // Getters and Setters

    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;

    }


    public double getSalary() {

        return salary;

    }


    public void setSalary(double salary) {

        this.salary = salary;

    }

}

Step 3: Serialize the Object to JSON

Use the ObjectMapper class to convert the Employee object into a JSON string.

import com.fasterxml.jackson.databind.ObjectMapper;


public class SerializationExample {

    public static void main(String[] args) {

        // Create an instance of Employee

        Employee employee = new Employee(101, "John Doe", "IT", 75000.50);


        // Create an ObjectMapper instance

        ObjectMapper objectMapper = new ObjectMapper();


        try {

            // Serialize the Employee object to JSON

            String json = objectMapper.writeValueAsString(employee);

            System.out.println("Serialized JSON:");

            System.out.println(json);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Output

The above code will produce the following JSON:

{

  "id": 101,

  "name": "John Doe",

  "department": "IT",

  "salary": 75000.5

}

Additional Features with Jackson

1. Pretty Printing

To generate a well-formatted JSON, use the writerWithDefaultPrettyPrinter() method:

String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);

System.out.println(prettyJson);

Output:

{
  "id": 101,
  "name": "John Doe",
  "department": "IT",
  "salary": 75000.5
}

2. Customizing Field Names

Use @JsonProperty annotation to customize the field names in JSON:

import com.fasterxml.jackson.annotation.JsonProperty;


public class Employee {

    @JsonProperty("employee_id")

    private int id;

    @JsonProperty("full_name")

    private String name;

    private String department;

    private double salary;


    // Constructors, Getters, and Setters

}

Output: 

{
  "employee_id": 101,
  "full_name": "John Doe",
  "department": "IT",
  "salary": 75000.5
}

3. Ignoring Fields

Use @JsonIgnore to exclude specific fields from the JSON payload:

import com.fasterxml.jackson.annotation.JsonIgnore;


public class Employee {

    private int id;

    private String name;

    private String department;

    @JsonIgnore

    private double salary;


    // Constructors, Getters, and Setters

}

Output:

{
  "id": 101,
  "name": "John Doe",
  "department": "IT"
}

Followers