How to Create Nested JSON Object Using POJO and Jackson API

In modern software development, JSON (JavaScript Object Notation) has become the de facto standard for data exchange. To work with JSON in Java, Jackson API is one of the most widely used libraries due to its simplicity and powerful features. In this blog post, we’ll explore how to create a nested JSON object using Plain Old Java Objects (POJO) with the Jackson API.


Prerequisites

Before we dive into coding, ensure that you have the following:

  1. Java Development Kit (JDK) installed.
  2. Jackson Library included in your project:
    • Add the following Maven dependency to your pom.xml if you're using Maven:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

What Is a Nested JSON Object?

A nested JSON object is a JSON structure where one or more JSON objects are embedded inside another JSON object. Here's an example:

{

  "employee": {

    "id": 101,

    "name": "John Doe",

    "contact": {

      "email": "john.doe@example.com",

      "phone": "123-456-7890"

    },

    "address": {

      "city": "New York",

      "zipCode": "10001"

    }

  }

}

This JSON represents an employee object with nested objects for contact and address.


Step-by-Step Guide to Creating Nested JSON Using POJO and Jackson

1. Define the POJOs

First, create Java classes that mirror the structure of your JSON. Each nested JSON object corresponds to a class.

Employee.java

public class Employee {
    private int id;
    private String name;
    private Contact contact;
    private Address address;

    // 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 Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}

Contact.java

public class Contact {
    private String email;
    private String phone;

    // Getters and Setters
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

Address.java

public class Address {
    private String city;
    private String zipCode;

    // Getters and Setters
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }
}

2. Populate POJOs with Data

Once the POJOs are ready, you can populate them with data:

public class Main {

    public static void main(String[] args) {

        // Create Address object

        Address address = new Address();

        address.setCity("New York");

        address.setZipCode("10001");


        // Create Contact object

        Contact contact = new Contact();

        contact.setEmail("john.doe@example.com");

        contact.setPhone("123-456-7890");


        // Create Employee object and set nested objects

        Employee employee = new Employee();

        employee.setId(101);

        employee.setName("John Doe");

        employee.setContact(contact);

        employee.setAddress(address);


        // Convert POJO to JSON

        try {

            ObjectMapper objectMapper = new ObjectMapper();

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

            System.out.println(json);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

3. Output

Running the above code will generate the following JSON:

{

  "id": 101,

  "name": "John Doe",

  "contact": {

    "email": "john.doe@example.com",

    "phone": "123-456-7890"

  },

  "address": {

    "city": "New York",

    "zipCode": "10001"

  }

}

Key Points to Remember

  1. POJO Structure: Ensure your POJOs reflect the JSON hierarchy.
  2. Jackson ObjectMapper: Use ObjectMapper to convert between POJOs and JSON.
  3. Pretty Printing: Use writerWithDefaultPrettyPrinter() for readable JSON output.
  4. Exception Handling: Always handle exceptions when working with JSON serialization.

Followers