1.Introduction

This short tutorial will show how to create a custom serializer with Jackson. We'll show how to create one and how to use it during the object serialization. If you want to know how to create a custom Jackson deserializer, check out this guide

Here, we'll create one class called Purchase. Then, we'll create PurchaseDTO class that will be served to clients. PurchaseDTO will have field purchaseDateTime of type LocalDateTime that we want to deserialize to ISO date-time

2. Implementation

We need to include Jackson in our project by adding it as a Maven dependency:

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

Also, it's part of spring-boot-starter-web dependency, so if you already added it, there's no need to manually add jackson-databind dependency.

Let's create our Purchase class:

@Entity
public class Purchase {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long itemId;
    private Long customerId;
    private LocalDateTime purchaseDateTime;
    
    // getters, setters, etc
}

And now, let's create our DTO class:

public class PurchaseDto {

    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime purchaseDateTime;
    private Long itemId;
 // getters, setters
}

Notice the @JsonSerialize annotation where we declared that we'll be using our custom serializer named LocalDateTimeSerializer.

And now, let's see how does our LocalDateTimeSerializer class look like:

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

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

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

    @Override
    public void serialize(LocalDateTime value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
        jsonGenerator.writeObject(value.format(DateTimeFormatter.ISO_DATE_TIME));
    }
}

For this example, we choose to use DateTimeFormatter.ISO_DATE_TIME format. You can check the available list of format types here.

Just for the record, you can also define the output format of Date by using the following annotation:

@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
LocalDateTime localDatetime;

We didn't use this since our idea was to show how to create a custom serializer with Jackson.

3. Conclusion

In this short tutorial, we showed how to create a custom serializer with Jackson. If you want to learn how to create a custom Jackson deserializer, check out this tutorial.