Spring Boot LocalDate field serialization and deserialization

前端 未结 4 1382
孤独总比滥情好
孤独总比滥情好 2020-12-17 01:37

On spring boot 1.2.3.RELEASE with fasterxml what is the correct way of serializing and de-serializing a LocalDate field to iso date formatted string?

I\'ve tried:

4条回答
  •  星月不相逢
    2020-12-17 02:10

    In my Spring Boot 2 applications

    • @JsonFormat annotation is used in REST controllers when (de)serializing JSON data.
    • @DateTimeFormat annotation is used in other controllers ModelAttributes when (de)serializing String data.

    You can specify both on the same field (useful if you share DTO between JSON and Thymeleaf templates):

    @JsonFormat(pattern = "dd/MM/yyyy") 
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private LocalDate birthdate;
    

    Gradle dependency:

    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-json'
    

    I hope this is all configuration you need for custom Date/Time formatting in Spring Boot 2.x apps.


    For Spring Boot 1.x apps, specify additional annotations and dependency:

    @JsonFormat(pattern = "dd/MM/yyyy")
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate birthDate;
    
    // or
    @JsonFormat(pattern = "dd/MM/yyyy HH:mm")
    @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime birthDateTime;
    
    implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8'
    

提交回复
热议问题