Main Tutorials

Jackson and Lombok examples

This article shows how to use Jackson and Lombok together.

Table of contents:

P.S Tested with Jackson 2.17.0 and Lombok 1.18.32

1. Download Jackson and Lombok

Declares jackson-databind and lombok at pom.xml.

pom.xml

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
  </dependency>

  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.32</version>
  </dependency>

2. Model with Lombok annotations

With Lombok annotation, we do not need to write boilerplate code such as getters, setters, constructors, and more.

Person.java

package com.mkyong.json.jackson.lombok;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    private String name;
    private int age;

}

Lombok Annotations Explained:

  • @Data: A Lombok annotation to generate getters, setters, toString, equals, and hashCode methods automatically.
  • @NoArgsConstructor: Generates a no-argument constructor.
  • @AllArgsConstructor: Generates a constructor with one argument for each field in the class.

3. Parse JSON using Jackson

The following example demonstrates the process of using Jackson to serialize a Java object Person, which is enhanced with Lombok annotations, to JSON and then deserialize it back:

PrettyPrintJsonExample.java

package com.mkyong.json.jackson.lombok;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonLombokExample {

    public static void main(String[] args) {

        try {

            ObjectMapper om = new ObjectMapper();

            Person person = new Person("mkyong", 42);

            // Serialize the Person object to JSON
            String jsonOutput = om.writeValueAsString(person);
            System.out.println("Serialized JSON: " + jsonOutput);

            // Deserialize the JSON back to a Person object
            Person deserializedPerson = om.readValue(jsonOutput, Person.class);
            System.out.println("Deserialized Person: " + deserializedPerson);

        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }
}

Output


Serialized JSON: {"age":42,"new_name":"mkyong"}
Deserialized Person: Person(name=mkyong, age=42)

5. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd jackson/lombok

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments