Convert Java Objects To JSON with Jackson API

A guide on How to use Jackson JSON API to Convert Java Objects To JSON. Converting an Object to JSON is also called Serialisation of the Object.

Overview

The JSON stands for JavaScript Object Notation. It is a text-based, lightweight data-interchange format. As JSON is a preferred format of data transfer between different systems, we often find a need to map Java Objects into JSON String.

This tutorial will see examples of using Jackson Databind API to create JSON Strings from Java POJO Classes.

Setup

Before we write our conversions, here are a few basic setups that we will do.

Jackson Dependency

First, add Jackson as a dependency in your project. Always refer to the latest version of Jackson Databind library from here.

Maven – pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>{version}</version>
</dependency>
Code language: HTML, XML (xml)

Or, Gradle – build.gradle

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '{version}'Code language: Gradle (gradle)

Create a Pojo

Let’s create a POJO class that we will use for the conversions.

StudentDto.java

package com.amitph.spring.tutorials.students.model;

public class StudentDto {
    private long id;
    private String firstName;
    private String lastName;
    private int joinedYear;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getJoinedYear() {
        return joinedYear;
    }

    public void setJoinedYear(int joinedYear) {
        this.joinedYear = joinedYear;
    }
}Code language: Java (java)

Now, we can have all the dependencies and the Java Pojo ready. Next, we will use Jackson to Convert the POJO to JSON.

Custom Java to JSON using Jackson

To convert or map Java POJO to JSON string, we have to create an instance of ObjectMapper class and use method writeValueAsString.

private static void objectToJson() throws JsonProcessingException {
    StudentDto studentDto = new StudentDto();
    studentDto.setId(1111L);
    studentDto.setFirstName("Strong");
    studentDto.setLastName("Belwas");
    studentDto.setJoinedYear(2022);

    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(studentDto);

    System.out.println(json);
}Code language: Java (java)

Here, we first create a POJO with some values and then use Jackson Object Mapper to convert the POJO into JSON.

The output JSON String looks like this.

{"id":1111,"firstName":"Strong","lastName":"Belwas","joinedYear":2022}Code language: JSON / JSON with Comments (json)

Simple Map to JSON using Jackson

The Map data structures are very similar to JSON structures. Hence, it is easy to represent Java maps into JSON strings.

private static void stringMapToJson() throws JsonProcessingException {
    Map<String, String> map = Map.of("one", "a", "two", "b");
    ObjectMapper objectMapper = new ObjectMapper();

    String json = objectMapper.writeValueAsString(map);

    System.out.println(json);
}Code language: Java (java)

Map of Custom Objects to JSON using Jackson

Next, we will create a map that hold StudentDto instance as value, and convert it to JSON String.

private static void objectMapToJson() throws JsonProcessingException {
    StudentDto studentDto = new StudentDto();
    studentDto.setId(1111L);
    studentDto.setFirstName("Strong");
    studentDto.setLastName("Belwas");
    studentDto.setJoinedYear(2022);

    Map<Long, StudentDto> map = Map.of(studentDto.getId(), studentDto);

    ObjectMapper objectMapper = new ObjectMapper();

    String json = objectMapper.writeValueAsString(map);

    System.out.println(json);
}Code language: Java (java)

Output:

{"1111":{"id":1111,"firstName":"Strong","lastName":"Belwas","joinedYear":2022}}
Code language: JSON / JSON with Comments (json)

Summary

We have learned to use Jackson Databind Library for JSON conversions in this practical tutorial. Also, we covered examples of converting Custom Java Objects or POJOs to JSON, Simple Maps to JSON, and Converting Map of Custom Objects to JSON using Jackson API.

For more Java Tutorials, please visit Java Tutorials.