方案一:Object对象接收强转成Java对象,需要先转成JSON对象,再转换成Java对象。
@Autowired
public RedisTemplate redisTemplate;
@Test
public void fastJson(){
/*
* redis 数据:
* {"@type":"xx.xx.GoodsDetailDTO","goodsName":"HK GOLD香港黄金","goodsPrice":100.00}
*
* 错误信息:
* java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to xx.xx.GoodsDetailDTO
*/
//@Version 1.2.72
GoodsDetailDTO goodsDetail;
//Object对象
Object object = this.getCacheObject(GoodsKeyConstant.GOODS_DETAIL_KEY + 1L);
if (Objects.nonNull(object)) {
//Object对象强转成Java对象
goodsDetail = (GoodsDetailDTO) object;
log.info("商品信息:{}", JSONObject.toJSONString(goodsDetail));
}
//@Version 2.0.14
//先转成JSON对象
JSONObject jsonObject = this.getCacheObject(GoodsKeyConstant.GOODS_DETAIL_KEY + 1L);
//JSON对象转换成Java对象
GoodsDetailDTO goodsDetailDTO = jsonObject.toJavaObject(GoodsDetailDTO.class);
log.info("商品信息:{}", JSONObject.toJSONString(goodsDetailDTO));
}
private <T> T getCacheObject(String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
本文介绍了如何在Redis中存储和获取Java对象,并通过两种方式实现序列化与反序列化:直接强转及先转为JSON对象再进行转换。展示了具体的代码示例及可能遇到的类型转换异常。
1万+

被折叠的 条评论
为什么被折叠?



