JSON序列化Redis读取出错问题解决方案
作者:贾树丙 时间:2022-10-13 18:57:50
报错
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.alibaba.fastjson.JSONException: syntax error, expect {, actual string, pos 1, fastjson-version 1.2.44
问题分析
在写入缓存的时候,hash结构,它的value值,在写入前使用JSON 序列化了,JSON.toJSONString(value)
在取缓存的时候把一个Collection 作为对象序列化了,并不是把List 序列化,所以在反序列化的时候不能用List 来解析
// 读取缓存返回String
BoundHashOperations<String, String, String> hash = this.template.boundHashOps(key);
Collection list = hash.entries().values();
return JSON.toJSONString(list);// 将String 解析成 List
String tmp = redisService.listHashObject(BOOK_CATALOG);
return JSON.parseArray(tmp, BookCatalog.class);
问题出在这里了,把Collection 转成List 出错 ,首先强转是不行的
解决
// 读取缓存直接返回 Collection
BoundHashOperations<String, String, String> hash = this.template.boundHashOps(key);
return hash.entries().values();// 将Collection 转成List,不能直接转成对象,需要先转换成String ,再将单个String 反序列化成对象
java.util.Collection tmp = redisService.listHashObject(BOOK_CATALOG);
List<String> list = new ArrayList<>(tmp);
List<BookCatalog> ans = new ArrayList<>(list.size());
for (String item : list) {
BookCatalog book = JSON.parseObject(item, BookCatalog.class);
ans.add(book);
}//可以再排个序,本身的hash 结构是无序的 ans.sort(Comparator.comparing(BookCatalog::getCode));
return ans;
来源:https://www.cnblogs.com/acm-bingzi/p/redis_fastjson.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C# 指针内存控制Marshal内存数据存储原理分析
Android MaterialAlertDialogBuilder修改按钮属性
![](https://img.aspxhome.com/file/2023/8/105988_0s.png)
Android开发从相机或相册获取图片裁剪
![](https://img.aspxhome.com/file/2023/2/137642_0s.png)
Android编程中自定义dialog用法实例
Java中ArrayList和SubList的坑面试题
![](https://img.aspxhome.com/file/2023/5/76625_0s.png)
SpringBoot jackson提供对LocalDate的支持方式
Android4.2中全屏或者取消标题栏的方法总结
C# 对象持久化详解
![](https://img.aspxhome.com/file/2023/7/83357_0s.png)
Java实现数据连接池Druid举例
C#实现组合排列的方法
![](https://img.aspxhome.com/file/2023/9/111229_0s.jpg)
C#动态编译并执行字符串样例
浅谈Android Studio如何Debug对应so文件C/C++代码
![](https://img.aspxhome.com/file/2023/2/89552_0s.jpg)
Spring Boot项目添加外部Jar包以及配置多数据源的完整步骤
Toast类避免显示时间叠加的方法
flutter 怎么实现app整体灰色效果
![](https://img.aspxhome.com/file/2023/7/137727_0s.jpg)
spring cloud升级到spring boot 2.x/Finchley.RELEASE遇到的坑
![](https://img.aspxhome.com/file/2023/6/90026_0s.jpg)
java身份证合法性校验工具类实例代码
Java开发中synchronized的定义及用法详解
![](https://img.aspxhome.com/file/2023/6/62226_0s.png)
Java入门绊脚石之Override和Overload的区别详解
![](https://img.aspxhome.com/file/2023/5/63445_0s.png)