解决Jackson2反序列化LocalDateTime报错

时间:2021-12-07 18:05:29

今天在整合redis和spring boot的时候,遇到了一个错误,记录一下。

报错如下:

Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

查看后发现是数据从redis中取出时,Jackson2反序列化数据处理LocalDateTime类型时出错,原因是:Jackson2在序列化LocalDateTime时输出的不是普通的字符串时间格式,而是如下所示的格式(普通时间格式:2019-02-27 12:10:17)

解决Jackson2反序列化LocalDateTime报错解决Jackson2反序列化LocalDateTime报错
{
    "date": {
        "year": 2019,
        "month": "FEBRUARY",
        "day": 27,
        "dayOfMonth": 27,
        "dayOfWeek": "WEDNESDAY",
        "era": [
            "java.time.chrono.IsoEra",
            "CE"
        ],
        "dayOfYear": 58,
        "leapYear": false,
        "chronology": {
            "id": "ISO",
            "calendarType": "iso8601"
        },
        "prolepticMonth": 24229,
        "monthValue": 2
    },
    "time": {
        "hour": 12,
        "minute": 10,
        "second": 17,
        "nano": 0
    },
    "month": "FEBRUARY",
    "year": 2019,
    "dayOfMonth": 27,
    "dayOfWeek": "WEDNESDAY",
    "dayOfYear": 58,
    "hour": 12,
    "minute": 10,
    "nano": 0,
    "second": 17,
    "monthValue": 2,
    "chronology": [
        "java.time.chrono.IsoChronology",
        {
            "id": "ISO",
            "calendarType": "iso8601"
        }
    ]
}
View Code

 

所以是Jackson2序列化LocalDateTime跟我们所预想的不一致,将注册给redis的序列化模板修改成以下就行

 1 @Configuration
 2 public class RedisConfig {
 3 
 4     /**
 5      * 定义 UserRedisTemplate ,指定序列化和反序列化的处理类
 6      *
 7      * @param factory redis连接工厂
 8      * @return 模板
 9      */
10     @Bean("UserRedisTemplate")
11     public RedisTemplate<String, User> userRedisTemplate(RedisConnectionFactory factory) {
12         RedisTemplate<String, User> template = new RedisTemplate<>();
13         template.setConnectionFactory(factory);
14         Jackson2JsonRedisSerializer<User> j2jrs = new Jackson2JsonRedisSerializer<>(User.class);
15         ObjectMapper om = new ObjectMapper();
16         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
17         // 解决jackson2无法反序列化LocalDateTime的问题
18         om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
19         om.registerModule(new JavaTimeModule());
20         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
21         j2jrs.setObjectMapper(om);
22         // 序列化 value 时使用此序列化方法
23         template.setValueSerializer(j2jrs);
24         template.setHashValueSerializer(j2jrs);
25         // 序列化 key 时
26         StringRedisSerializer srs = new StringRedisSerializer();
27         template.setKeySerializer(srs);
28         template.setHashKeySerializer(srs);
29         template.afterPropertiesSet();
30         return template;
31     }
32 }

主要是加上标红的那两句

 

参考文档:

GenericJackson2JsonRedisSerializer 反序列化问题