HelloWhatsMyName1234
HelloWhatsMyName1234

Reputation: 105

Jackson objectMapper, trying to serialize LocalDate into "yyyy-MM-dd" and LocalTime into "HH:mm:ss"

So I have an object like this

    @EqualsAndHashCode
@Builder
@NoArgsConstructor
@Getter
@Setter
@AllArgsConstructor
public class CreateBookingDto implements Serializable {
    @JsonFormat(pattern="yyyy-MM-dd")
    private LocalDate date;
    @JsonFormat(pattern="HH:mm:ss")
    private LocalTime startTime;
}

I am trying to map it to a string and I get it a string like this

"{
"date":
{"year":2021,"month":"JANUARY","dayOfWeek":"SATURDAY","era":"CE","chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfYear":16,"leapYear":false,"monthValue":1,"dayOfMonth":16},
"startTime":
{"hour":16,"minute":33,"second":13,"nano":721065000}}"

How Can I map them to a string in the format "yyyy-mm-dd" for the date and "HH:mm:ss" for the time

How I am mapping the object

def objectMapper = new ObjectMapper()
def requestBodyJson = new ObjectMapper().writeValueAsString(dtoObject)

My pom

        <dependency>
        <groupId>com.fasterxml.jackson</groupId>
        <artifactId>jackson-bom</artifactId>
        <version>2.12.1</version>
        <type>pom</type>
    </dependency>

Upvotes: 2

Views: 3840

Answers (2)

LoBo
LoBo

Reputation: 212

If you don't wish to add additional dependency to your project, you can create a serializer yourself. Annotate your member:

@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate date;

and create the serializer:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateSerializer extends StdSerializer<LocalDate> {

    private static final long serialVersionUID = -4746126944463708083L;

    public LocalDateSerializer() {
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider sp) throws IOException {
        if (value != null) {
            generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
    }
}

Upvotes: 0

Thomas Fritsch
Thomas Fritsch

Reputation: 10145

You need to register the JavaTimeModule to your ObjectMapper. This will install a bunch of JSON serializers/deserializers for classes of the java.time package.
(And by the way: in your line 2, use the ObjectMapper from line 1, instead of creating a new one.)

def ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
def requestBodyJson = objectMapper.writeValueAsString(dtoObject)

Then the JSON output will be like this:

{"date":"2021-01-17","startTime":"22:59:15"}

Upvotes: 3

Related Questions