"yyyy-MM-dd HH:mm:ss"格式日期字符串 json反序列化成LocalDateTime类型问题

问题描述:

前端传递日期格式
在这里插入图片描述
后台接收类日期对象定义
在这里插入图片描述
后台controller类处理请求代码
在这里插入图片描述
springboot中默认使用jackson做json序列化和反序列化,后台接收数据时将上述日期字符串转成LocalDateTime时,会报如下错误:

JSON parse error: Cannot deserialize value of type java.time.LocalDateTime from String “2018-09-20 08:01:00”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2018-09-20 08:01:00’ 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 “2018-09-20 08:01:00”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2018-09-20 08:01:00’ could not be parsed at index 10

解决办法:

如果不做处理,jackson 只能将"2018-09-20T08:01:00"转成LocalDateTime,而
"2018-09-20 08:01:00"是不能转成LocalDateTime的,但"2018-09-20T08:01:00"不符合我们的阅读习惯,而且前端传这种格式的日期字符串也很麻烦,这时你可能想到把接收类中的LocalDateTime类型改成String类型,后台接收后再在代码中转成LocalDateTime类型做日期处理。
那还有没有别的更好的办法解决这个问题呢?如下:

步骤一:引入jackson日期工具包jsr310
pom文件引入jsr310
在这里插入图片描述

步骤二:
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;

}
在这里插入图片描述

这样"2018-09-20 08:01:00"日期字符串就可以被正常反序列化成LocalDateTime类型的日期了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值