Spring Boot LocalDate字段序列化和反序列化

ayc*_*dal 4 serialization json date spring-data-rest spring-boot

在spring boot 1.2.3.RELEASE with fasterxml什么是将LocalDate字段序列化和反序列化为iso日期格式化字符串的正确方法?

我试过了:

application.properties文件中的spring.jackson.serialization.write-dates-as-timestamps:false,

包括项目中的jackson-datatype-jsr310然后使用

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") 注解

和@DateTimeFormat(iso=ISO.DATE)注释,

将Jsr310DateTimeFormatAnnotationFormatterFactory添加为格式化程序:

@Override public void addFormatters(FormatterRegistry registry){registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory()); }

以上都没有帮助.

ayc*_*dal 20

compile ("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
Run Code Online (Sandbox Code Playgroud)

在build.gradle中,然后在注释后帮助:

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthday;
Run Code Online (Sandbox Code Playgroud)

更新:如果您使用的是Spring Boot 2.*,则必须通过其中一个"starters"包含依赖项.


naX*_*aXa 10

在我的 Spring Boot 2 应用程序中

  • @JsonFormat 当(反)序列化 JSON 数据时,在 REST 控制器中使用注释。
  • @DateTimeFormatModelAttribute当(反)序列化 String 数据时,在其他控制器中使用注释。

您可以在同一字段中指定两者(如果您在 JSON 和 Thymeleaf 模板之间共享 DTO,则很有用):

@JsonFormat(pattern = "dd/MM/yyyy") 
@DateTimeFormat(pattern = "dd/MM/yyyy")
private LocalDate birthdate;
Run Code Online (Sandbox Code Playgroud)

Gradle依赖:

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-json'
Run Code Online (Sandbox Code Playgroud)

我希望这是在 Spring Boot 2.x 应用程序中自定义日期/时间格式所需的所有配置。


对于 Spring Boot 1.x 应用程序,指定附加注释和依赖项:

@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;
Run Code Online (Sandbox Code Playgroud)
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8'
Run Code Online (Sandbox Code Playgroud)


Rad*_*FID 5

如果您想使用自定义 Java 日期格式化程序,请添加注释 @JsonFormat。

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthdate;*
Run Code Online (Sandbox Code Playgroud)


小智 5

实际上,只要在 pom.xml 中指定依赖项就可以了。

这样,我的所有 LocalDate 字段都会自动使用 ISO 格式,无需注释它们:

<!-- This is enough for LocalDate to be deserialized using ISO format -->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在 Spring Boot 1.5.7 上测试。