在我的 Spring Boot 2 应用程序中
-
@JsonFormat 注解在(反)序列化 JSON 数据时在 REST 控制器中使用。
-
@DateTimeFormat 注解在其他控制器中使用 ModelAttributes 在(反)序列化字符串数据时。
您可以在同一个字段上指定两者(如果您在 JSON 和 Thymeleaf 模板之间共享 DTO,这很有用):
@JsonFormat(pattern = "dd/MM/yyyy")
@DateTimeFormat(pattern = "dd/MM/yyyy")
private LocalDate birthdate;
Gradle 依赖:
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-json'
我希望这是您在 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;
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.9.8'
请注意,如果有人以错误的格式发送日期,您的 API 将抛出“JSON 解析错误”。映射示例:
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate releaseDate;
异常示例:
HttpMessageNotReadableException:JSON 解析错误:无法从字符串“2002”反序列化 java.time.LocalDate 类型的值:无法反序列化 java.time.LocalDate:(java.time.format.DateTimeParseException)无法在索引 4 处解析文本“2002”;嵌套异常是com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串“2002”反序列化java.time.LocalDate 类型的值:无法反序列化java.time.LocalDate:(java.time.format.DateTimeParseException)无法在索引4 处解析文本“2002”