This article shows how to use Jackson and Lombok together.
Table of contents:
- 1. Download Jackson and Lombok
- 2. Model with Lombok annotations
- 3. Parse JSON using Jackson
- 5. Download Source Code
- 6. References
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
- Lombok
- Jackson Github
- Parse JSON string with Jackson
- Parse JSON Array with Jackson
- Convert Java Objects to JSON with Jackson
- How to map a subset of a JSON file using Jackson
The post Jackson and Lombok examples appeared first on Mkyong.com.