報錯
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