Jackson Custom Serializer and Deserializer Examples

This article shows how to create a Jackson custom serializer and deserializer to parse JSON data that contains a LocalDate type. The Jackson custom serializer or deserializer is useful when we want to process a specific format that is not the default.

Table of contents:

P.S Tested with Jackson 2.17.0

1. Setup Jackson

Puts jackson-databind at pom.xml.

pom.xml

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

2. Jackson Custom Serializer for LocalDate

The following example creates a custom serializer to convert the LocalDate type to JSON.

LocalDateSerializer.java

package com.mkyong.json.jackson.tips;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateSerializer extends JsonSerializer<LocalDate> {
    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("dd-MM-yyyy");

    @Override
    public void serialize(LocalDate value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeString(formatter.format(value));
    }

}

3. Jackson Custom Deserializer for LocalDate

The following example creates a custom deserializer to convert the JSON field that contains dates as strings, and we want to convert them to the Localdate type.

LocalDateDeserializer.java

package com.mkyong.json.jackson.tips;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {
        return LocalDate.parse(p.getValueAsString(), formatter);

    }
}

4. Registering Custom with SimpleModule

In Jackson, we use a SimpleModule and register the custom serializer and deserializer and add it to the main ObjectMapper.

CustomSerializerExample.java

package com.mkyong.json.jackson.tips;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.time.LocalDate;

public class CustomSerializerExample {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();

        // Registering the custom serializer and deserializer
        module.addSerializer(LocalDate.class, new LocalDateSerializer());
        module.addDeserializer(LocalDate.class, new LocalDateDeserializer());

        // Register the module with the ObjectMapper
        mapper.registerModule(module);

        // Example usage: Serialize and deserialize a LocalDate
        LocalDate date = LocalDate.of(2024, 5, 30);

        try {
            String serializedDate = mapper.writeValueAsString(date);
            System.out.println("Serialized date: " + serializedDate);

            LocalDate deserializedDate = mapper.readValue("\"2024-05-30\"", LocalDate.class);
            System.out.println("Deserialized date: " + deserializedDate);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output


Serialized date: "30-05-2024"
Deserialized date: 2024-05-30

5. Download Source Code

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

$ cd jackson

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