RedisTemplate反序列化提取报错:class java.util.LinkedHashMap cannot be cast to class com.alibaba.fastjson.JSONObject

原因是:

使用Jackson2JsonRedisSerializer序列化后的数据形式,如下:

{"port":xxxx,"ip":"106.xxx.xxx.xxx","expire_time":"2021-02-04 20:53:28"}

为什么会报错?

序列化带泛型的数据时,会以map的结构进行存储,反序列化是不能将map解析成对象

 

解决方案:

1.序列化存储时,转成JSON字符串:redisTemplate.opsForValue().set("test3", JSON.toJSONString(userToken),5,TimeUnit.MINUTES);(此方法也是不能强转)

2.GenericJackson2JsonRedisSerializer序列化反序列化

 

使用GenericJackson2JsonRedisSerializer序列化后的数据形式,如下:

{"@class":"com.alibaba.fastjson.JSONObject","port":xxxx,"ip":"113.xxx.xxx.xxx","expire_time":"2021-02-04 21:07:35"}

使用GenericJackson2JsonRedisSerializer序列化时,会保存序列化的对象的包名和类名,反序列化时以这个作为标示就可以反序列化成指定的对象。

 

 

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐