问题描述:
前端传递日期格式
后台接收类日期对象定义
后台controller类处理请求代码
springboot中默认使用jackson做json序列化和反序列化,后台接收数据时将上述日期字符串转成LocalDateTime时,会报如下错误:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2019-01-15 19:40:59": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-01-15 19:40:59' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2019-01-15 19:40:59": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-01-15 19:40:59' could not be parsed at index 10
at [Source: (PushbackInputStream); line: 10, column: 19] (through reference chain: com.fe.topic.dto.TopicDto["createTime"])]
解决办法:
如果不做处理,jackson 只能将"2019-01-15T19:40:59"转成LocalDateTime,而
"2019-01-15 19:40:59"是不能转成LocalDateTime的,但"2019-01-15T19:40:59"不符合我们的阅读习惯,而且前端传这种格式的日期字符串也很麻烦,这时你可能想到把接收类中的LocalDateTime类型改成String类型,后台接收后再在代码中转成LocalDateTime类型做日期处理。
另一种解决方法:
步骤一:引入jackson日期工具包jsr310
pom.xml文件引入jsr310
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.0</version>
</dependency>
步骤二:
springboot 启动类中加入如下代码:
@Bean
public ObjectMapper serializingObjectMapper() {
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(module)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
return objectMapper;
}
这样"2019-01-15 19:40:59"日期字符串就可以被正常反序列化成LocalDateTime类型的日期了