背景
- Java序列化工具用的是jackson
- 序列化实体类的时候有
LocalDateTime
属性
最开始发现问题是因为用jackson的时候json字符串转实体类报错,报错内容:
JSON parse error: Cannot deserialize value of type
java.time.LocalDateTime
from String "2022-06-16 18:32:41": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-06-16 18:32:41' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of typejava.time.LocalDateTime
from String "2022-06-16 18:32:41": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-06-16 18:32:41' could not be parsed at index 10\n at [Source: (PushbackInputStream); line: 3, column: 16]
原因是因为大家通常时间序列化成字符串的时候都是yyyy-MM-dd HH:mm:ss
但是jackson默认的是国际化的时间标准
yyyy-MM-ddTHH:mm:ss
区别就自安于中间多了个T,所以我们需要重写一个jackson的序列化工具
处理办法
springboot有个版本加入了jackson-datatype-jsr310
这个依赖,我的是2.5.1,如果没有的话可以手动引一下
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.12.3</version>
</dependency>
然后写一个方法来覆盖原有的Bean,这样就行了
@Component
public class LocalDateTimeSerializerConfig {
@Bean
public ObjectMapper serializingObjectMapper() {
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer dateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTimeSerializer dateTimeSerializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
module.addDeserializer(LocalDateTime.class, dateTimeDeserializer);
module.addSerializer(LocalDateTime.class, dateTimeSerializer);
return Jackson2ObjectMapperBuilder.json().modules(module)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build();
}
}