How to Create JSON Array Payload Using POJO – Jackson API

 In modern web applications, data exchange often happens through JSON format, which is lightweight and easy to process. When working with RESTful APIs in Java, it is crucial to understand how to convert data between Java objects (POJOs) and JSON format efficiently. Jackson, a popular Java library, provides powerful features for serializing and deserializing objects.

In this blog, we will walk you through how to create a JSON array payload using POJO with Jackson API.

What is POJO?

POJO stands for Plain Old Java Object. It is a simple Java object that doesn't extend or implement any specialized classes or interfaces. POJOs are used to hold data and provide getters and setters for manipulating the data. They are often used as data containers when dealing with JSON or other serialization formats.

What is Jackson API?

Jackson is a high-performance JSON processor for Java. It can convert Java objects to JSON (serialization) and vice versa (deserialization). Jackson provides a variety of annotations and features for fine-tuning the JSON output.

Jackson Features:

  • ObjectMapper: Main class for reading and writing JSON.
  • Annotations: @JsonProperty, @JsonCreator, @JsonIgnore, etc., for customizing serialization.
  • Streaming API: For efficient parsing of large JSON files.

Steps to Create JSON Array Payload Using POJO – Jackson API

Let’s break this down step by step. We'll create a simple example to serialize a list of POJOs into a JSON array using Jackson API.

Step 1: Add Jackson Dependencies

First, add the Jackson dependencies to your project. If you are using Maven, include the following in your pom.xml:

<dependencies>

    <dependency>

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

        <artifactId>jackson-databind</artifactId>

        <version>2.15.0</version>

    </dependency>

</dependencies>

For Gradle, use this:

dependencies {
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.0'
}

Step 2: Create a POJO Class

Let’s assume we are building a User object with some basic properties such as id, name, and email.

import com.fasterxml.jackson.annotation.JsonProperty;


public class User {

    

    @JsonProperty("id")

    private int id;

    

    @JsonProperty("name")

    private String name;

    

    @JsonProperty("email")

    private String email;


    // Constructor

    public User(int id, String name, String email) {

        this.id = id;

        this.name = name;

        this.email = email;

    }


    // 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 getEmail() {

        return email;

    }


    public void setEmail(String email) {

        this.email = email;

    }

}

Step 3: Create a List of POJOs

Now, let’s create a list of User objects. This will be the collection that we will convert into a JSON array.

import java.util.ArrayList;

import java.util.List;


public class UserList {

    public static void main(String[] args) {

        

        List<User> users = new ArrayList<>();

        users.add(new User(1, "John Doe", "john@example.com"));

        users.add(new User(2, "Jane Smith", "jane@example.com"));

        users.add(new User(3, "Emily Davis", "emily@example.com"));

        

        try {

            // Create ObjectMapper instance

            ObjectMapper objectMapper = new ObjectMapper();


            // Convert List of POJOs to JSON Array

            String jsonArray = objectMapper.writeValueAsString(users);

            System.out.println("JSON Array Payload: " + jsonArray);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Step 4: Convert POJO List to JSON Array

In the above code, we:

  1. Created a list of User objects.
  2. Used Jackson's ObjectMapper to convert the list of User objects into a JSON array format using writeValueAsString().
  3. Printed the resulting JSON array to the console.

The ObjectMapper is the central class in Jackson, and writeValueAsString() serializes the Java objects into JSON. The output of the above code will look something like this:

[

  {"id":1,"name":"John Doe","email":"john@example.com"},

  {"id":2,"name":"Jane Smith","email":"jane@example.com"},

  {"id":3,"name":"Emily Davis","email":"emily@example.com"}

]

Step 5: Handle Customizations (Optional)

If you need to customize the way the JSON is serialized (e.g., changing field names or excluding some fields), you can use Jackson annotations.

For example, you can exclude the email field in the JSON output by using @JsonIgnore:

import com.fasterxml.jackson.annotation.JsonIgnore;


public class User {

    private int id;

    private String name;


    @JsonIgnore

    private String email;


    // Constructor, getters, and setters

}

Now, when the list of users is serialized, the email field will be ignored.

Followers