SpringBoot中LocalDateTime序列化与反序列化配置(异常解决)

该博客讨论了在处理JSON输入时遇到的 LocalDateTime 类型反序列化异常。异常信息指出无法将字符串 '2021-7-2115:21:13' 转换为 LocalDateTime,原因是格式不匹配。为了解决这个问题,作者提供了一个配置类 LocalDateTimeSerializingConfig,通过自定义 ObjectMapper 并注册 JavaTimeModule 来指定 LocalDateTime 的序列化和反序列化格式,确保日期时间格式为 'yyyy-MM-dd HH:mm:ss'。

问题

异常信息:
Invalid JSON input: Cannot deserialize value of type java.time.LocalDateTime from String “2021-7-21 15:21:13”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2021-7-21 15:21:13’ could not be parsed at index 5; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDateTime from String “2021-7-21 15:21:13”: Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text ‘2021-7-21 15:21:13’ could not be parsed at index 5\n at [Source: (PushbackInputStream); line: 2, column: 18]

解决

加入配置类.实体类中的字段不要加@JsonFormat注解

/**
 * localDateTime反序列化配置
 */
@Configuration
public class LocalDateTimeSerializingConfig {
    private String localDateTimeFormat="yyyy-MM-dd HH:mm:ss";
    private String localDateFormat="yyyy-MM-dd";
    private String localTimeFormat="HH:mm:ss";

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper om = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //序列化
        javaTimeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimeFormat)));
        javaTimeModule.addSerializer(LocalDate.class,
                new LocalDateSerializer(DateTimeFormatter.ofPattern(localDateFormat)));
        javaTimeModule.addSerializer(LocalTime.class,
                new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimeFormat)));
        //反序列化
        javaTimeModule.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimeFormat)));
        javaTimeModule.addDeserializer(LocalDate.class,
                new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDateFormat)));
        javaTimeModule.addDeserializer(LocalTime.class,
                new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimeFormat)));
        om.registerModule(javaTimeModule);
        return om;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值