com.alibaba.fastjson.JSONObject cannot be cast to xxx

问题描述:通过redis读取的缓存对象用Object去接,因为我们已经知道他具体是什么类型了,所以接来的对象直接转换,报了上述错误。

这里其实我们已经对该实体类完成了序列化与反序列化。

 

public class LoginUser implements  Serializable 
LoginUser loginUser=redisCache.getCacheObject(redisKey);
    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

但是会报错com.alibaba.fastjson.JSONObject cannot be cast to xxx

 

解决方案:将得到的对象toString,再通过JSON.parseObject转成对应的对象

String string = redisCache.getCacheObject(redisKey).toString();
LoginUser loginUser=JSON.parseObject(string, LoginUser.class);

 

posted @ 2024-07-21 19:49  天启A  阅读(1136)  评论(0)    收藏  举报