Java Jackson ObjectMapper

How to work with Java and JSON? Sometimes in Java we need to work with different type data formats. One very common is JSON. In this tutorial we will see how to use popular Java library Jackson to read and write from JSON format.

To work with external libraries like jackson-databind we can download the jar and manually added to the project or we can use Maven to do this for us. In this tutorial we are using Maven.

The structure of the project look like this:

Java Maven project structure. Inside we have two classes Main and Person and pom.xml file

Let’s see our pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation=
                 "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>JacksonObjectMapperExample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.14.0</version>
        </dependency>

    </dependencies>

</project>

We use two libraries jackson-databind which is standard library if we want to work with JSON and jackson-datatype-jsr310 if we want to work with the new JAVA 8 Date/Time API (classes like LocalDate, LocalTime and LocalDateTime)

Then we have our POJO class Person:

package org.example;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.time.LocalDate;

public class Person {
    @JsonProperty("name")
    private String name;

    @JsonProperty("age")
    private Integer age;

    // with @JsonFormat we can add the date format in the JSON
    @JsonProperty("birthDate")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private LocalDate birthDate;

    // Default constructor is used from Jackson
    public Person(){}
    public Person(String name, Integer age, LocalDate birthDate) {
        this.name = name;
        this.age = age;
        this.birthDate = birthDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthDate=" + birthDate +
                '}';
    }
}

Inside we use two annotation JsonProperty (to set the output JSON property) and JsonFormat (to add specific format for LocalDate birthDate)

Then in our Main class we have methods:

  • writeSingleObjectToJSON -> for writing one java object from class Person to file target/one-person.json and also as String
  • readNodesOfJson -> reading JSON and get the nodes with JsonNode. In this case we donĀ“t need Person class to work with the JSON
  • readObjectOfPersonFromJson -> creating Person object from JSON
  • readMapOfPersonDataFromJson -> create Map with JSON keys and JSON values. Here we also do not need Person class
  • readListOfPeopleFromJson -> create List with people from JSON
package org.example;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException {

        writeSingleObjectToJSON();

        readNodesOfJson();

        readObjectOfPersonFromJson();

        readMapOfPersonDataFromJson();

        readListOfPeopleFromJson();

    }

    private static void writeSingleObjectToJSON() throws IOException {
        Person person = new Person("Raegan Olson", 45, LocalDate.of(1983, Month.AUGUST, 12));

        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.registerModule(new JavaTimeModule());

        // if I need to export to file
        objectMapper.writeValue(new File("target/one-person.json"), person);

        // if we need the object as String
        String personAsJsonString = objectMapper.writeValueAsString(person);
        System.out.println("Output from write Single object to JSON");
        System.out.println(personAsJsonString);
    }

    private static void readNodesOfJson() throws JsonProcessingException {
        String personAsJsonString = """
                {"name":"Axel Doyle","age":29,"birthDate":"1993-08-12"}
                """;
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        JsonNode jsonNode = objectMapper.readTree(personAsJsonString);
        String name = jsonNode.get("name").asText();
        Integer age = jsonNode.get("age").asInt();
        String date = jsonNode.get("birthDate").asText();
        System.out.println(" Age of " + name + " is: " + age + " date is: " + date);
    }

    private static void readObjectOfPersonFromJson() throws JsonProcessingException {
        String personAsJsonString = """
                {"name":"Charles Beasley","age":22,"birthDate":"1983-08-12"}
                """;
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        Person person = objectMapper.readValue(personAsJsonString, new TypeReference<>(){});

        System.out.println();
        System.out.println("Output from read Object of Person from JSON");
        System.out.println("Person from String: " + person);
    }

    private static void readMapOfPersonDataFromJson() throws JsonProcessingException {
        String personAsJsonString = """
                {"name":"Tianna Fernandez","age":43,"birthDate":"1976-09-10"}
                """;

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        Map<String, Object> map = objectMapper
                                    .readValue(personAsJsonString, new TypeReference<>(){});
        System.out.println();
        System.out.println("Output from read Map from JSON");
        map.forEach((k, v) -> System.out.println("Key: " + k + " has value: " + v));
    }

    private static void readListOfPeopleFromJson() throws IOException {
        String personAsJsonString = """
                [
                    {"name":"Emma Perez","age":10,"birthDate":"2010-01-01"},
                    {"name":"Alexander Joseph","age":11,"birthDate":"2009-01-01"}
                ]
                """;

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        List<Person> people = objectMapper.readValue(personAsJsonString, new TypeReference<>(){});

        System.out.println();
        System.out.println("Output from read List of people");
        people.forEach(p -> System.out.println(p));

        // if I need to export to file
        objectMapper.writeValue(new File("target/people.json"), people);
    }
}

Output:

Output from write Single object to JSON
{"name":"Raegan Olson","age":45,"birthDate":"1983-08-12"}
 Age of Axel Doyle is: 29 date is: 1993-08-12

Output from read Object of Person from JSON
Person from String: Person{name='Charles Beasley', age=22, birthDate=1983-08-12}

Output from read Map from JSON
Key: name has value: Tianna Fernandez
Key: age has value: 43
Key: birthDate has value: 1976-09-10

Output from read List of people
Person{name='Emma Perez', age=10, birthDate=2010-01-01}
Person{name='Alexander Joseph', age=11, birthDate=2009-01-01}

You can find GitHub repository with the example code here

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.