重剑无锋,大巧不工 SpringBoot --- Jackson 关于日期时间的注解

说明

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”) : 后端 =>前端的转换
@DateTimeFormat(pattern = “yyyy-MM-dd’T’HH:mm:ss”) : 前端 => 后端的转换
@JsonDeserialize(using = LocalDateTimeDeserializer.class) : jackson 反序列化
@JsonSerialize(using = LocalDateTimeSerializer.class): jackson 序列化

注意:

  1. 当 @JsonFormat 和 @JsonDeserialize 或者 @JsonSerialize 同时存在时, @JsonFormat 优先级更高

  2. @JsonFormat不仅可以完成后台到前台参数传递的类型转换,还可以实现前台到后台类型转换。

当content-type为application/json时,优先使用@JsonFormat的pattern进行类型转换。而不会使用@DateTimeFormat进行类型转换。

SpringBoot4 Jackson 配置记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Bean
public JsonMapperBuilderCustomizer customizer() {
return builder -> {
builder.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
builder.changeDefaultPropertyInclusion(incl ->
incl.withValueInclusion(JsonInclude.Include.ALWAYS));

builder.addModule(
new SimpleModule()
// Long 的序列化
.addSerializer(Long.class, StringSerializer.instance)
// LocalDateTime 的序列化
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
// LocalDateTime 的反序列化
.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
};
}