LocalDate Serialization: date as array?

偶尔善良 提交于 2021-02-10 14:53:48

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/60925899/localdate-serialization-date-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!