方案一: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);
}