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

本文介绍如何在SpringBoot中处理前端传递的不标准日期格式,通过配置Jackson将2019-01-1519:40:59格式的字符串正确反序列化为LocalDateTime。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

前端传递日期格式

后台接收类日期对象定义

后台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类型的日期了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值