侧边栏壁纸
博主头像
一只小松徐吖博主等级

A Good Boy ⛵️⛵️⛵️

  • 累计撰写 41 篇文章
  • 累计创建 40 个标签
  • 累计收到 7 条评论

目 录CONTENT

文章目录

Spring Boot 通用解决 LocalDateTime (反)序列化问题

超级管理员
2021-08-26 / 0 评论 / 10 点赞 / 995 阅读 / 2287 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-02-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

我们在 JDK8 环境中开发使用 LocalDateTime 的时候经常会遇到以下异常:

org.springframework.http.converter.HttpMessageNotReadableException:

JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2020-04-21 11:15:10": 

Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-04-21 11:15:10' 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 "2020-04-21 11:15:10": 
Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-04-21 11:15:10' could not be parsed at index 10
at [Source: (PushbackInputStream); line: 11, column: 16] ...

LocalDateTime 是 JDK8 的新特性,并且 LocalDateTime 默认的时间格式是: yyyy-MM-ddTHH:mm:ss,中间多了一个 T 字。我们正常交互上是没有这种 T 字的,所以会造成前后端交互数据的时候出现异常。

解决方法可参考下面代码:

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 解决 LocalDateTime 中间含 T 的问题
 *
 * @author xiaoxuxuy
 * @date 2021/6/9 10:53 上午
 */
@Configuration
public class LocalDateTimeConfiguration {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

            // 返回时间数据序列化
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));

            // 接收时间数据反序列化
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }
}
10
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区