问题遇到的现象和发生背景
最近在使用LocalDateTime返回前段时遇到的问题过程如下;
1. 刚开始直接使用@JsonFormat()注解,返回
@ApiModelProperty(name = "rksj", value = "入库时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime hcsj;
swagger得到的结果是
"hcsj": {
"month": "APRIL",
"year": 2022,
"dayOfMonth": 18,
"hour": 20,
"minute": 8,
"monthValue": 4,
"nano": 0,
"second": 15,
"dayOfWeek": "MONDAY",
"dayOfYear": 108,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
}
2. 第二步,引入了依赖
<!--jackson localdatetime格式化-->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
@ApiModelProperty(name = "rksj", value = "入库时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime rksj;
结果如下
# 不加@JsonFormat()注解时
"hcsj": [
2022,
4,
18,
20,
8,
15
]
# 加上@JsonFormat()注解时
"hcsj": "2022-04-18 20:08:15"
3. 配置类
在网上看到了序列化和反序列化配置类
@Configuration
public class LocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
/**
* localDateTime 序列化器
*/
@Bean
public LocalDateTimeSerializer localDateTimeSerializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
/**
* localDateTime 反序列化器
*/
@Bean
public LocalDateTimeDeserializer localDateTimeDeserializer() {
return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
builder.deserializerByType(LocalDateTime.class,localDateTimeDeserializer());
builder.simpleDateFormat(pattern);
};
}
}
但是如果不在字段上使用@JsonFormat()注解,结果如下:
"hcsj": [
2022,
4,
18,
20,
8,
15
]
4. 前端传输时间转换
之前都是使用@DateTimeFormat()注解
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
但是这个使用这个注解时报错了
Caused by: java.time.format.DateTimeParseException: Text '2022-04-19 20:08:15' could not be parsed at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:100)
... 92 common frames omitted
然后在请求体的字段上添加注解如下后
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
成功
我的问题
因为在网上看到的这些信息都很碎,或者没讲到底是因为什么,我想知道
- 明明引入依赖后,使用注解就可以达到目的了,为什么还要使用配置类+注解
- 之前@JsonForma()用于后端格式化时间传输到前端;@DateTimeFormat()将前端传输的时间格式化,在这里为什么失效了呢?__
- 有没有将这块写的清楚的文章推荐一下呢
最后谢谢各位同学的帮助