LocalDate Serialization: date as array?

I use Java 11 and want to serialize/deserialize LocalDate/LocalDateTime as String. Okay. I added dependency:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>${jackson.version}</version>
    </dependency>

and module:

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}

When I send date to my app, it deserializes correctly:

{"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}

When I using objectMapper as bean, directly, it serializes correctly too:

{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}

But when it serializes with controller, it serializes as array:

{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":[2008,3,20],"relativeType":"SON","cohabitants":true}

Problem is to deserialize date in body on controller. Controller is:

@PostMapping
public Relative create(@Validated(Validation.Create.class) @RequestBody Relative relative) {
    return service.create(relative);
}

Relative.class:

@Getter
@Setter
@ToString(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Relative extends MortgageResponse {

    @Null(groups = Validation.Create.class)
    @NotNull(groups = Validation.Update.class)
    private Long id;

    @NotNull
    private Long profileId;

    private LocalDate birthDate;
    private RelativeType relativeType;
    private Boolean cohabitants;
}

Please, advice me, what's problem and how to fix it.

Upvotes: 16

Views: 14897

Answers (3)

cejchank
cejchank

Reputation: 21

You can set the Date Format in your mapper. In your case it would be something like this:

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .setDateFormat(SimpleDateFormat("yyyy-MM-dd"));
}

You can change the format to whatever you need, e.g.yyyy-MM-dd HH:mm:ss, yyyy-dd-MM HH:mm:ss etc.

Upvotes: 2

Nirbhay Rana
Nirbhay Rana

Reputation: 4357

In your response class/dto add @JsonFormat(pattern="yyyy-MM-dd") on LocalDate field.

Upvotes: 0

Marco Behler
Marco Behler

Reputation: 3724

Add the @JsonFormat annotation to your birthDate field , or rather any date field and your ObjectMapper (Spring Boot or not) should respect the formatting, as long as you have the additional js310 dependency on your classpath.

@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthDate;

Upvotes: 26

Related Questions