解决fastJson反序列化问题 com.alibaba.fastjson.JSONObject cannot be cast to 的问题

解决问题 com.alibaba.fastjson.JSONObject cannot be cast to 的问题

问题描述

最近在学习redis的使用。有个简单的查询逻辑即查询前先从redis取,取到后则进行反序列化。如下:

String resJson = redisService.getString(name);
if (StringUtil.isNotEmpty(resJson)) {
    
    
    // 反序列化
    return (ResultVo)JSON.parse(resJson);
}

使用了JSON.parse()来将redis中存的json字符串进行解析并强转为我需要的ResultVo对象。
代码运行时就报了错:
报错

问题解决

不能直接强转,JSON.parse(String)方法 只能解析为JsonObject对象。
如果想要解析为指定对象,需要使用JSON.parseObject(String text, Class clazz)方法
需要注意的是:使用该方法,指定的类必须有无参构造方法。

String resJson = redisService.getString(name);
if (StringUtil.isNotEmpty(resJson)) {
    
    
	// 反序列化
    return JSON.parseObject(resJson, ResultVo.class);
}

问题扩展

如果想解析为为List<指定类> 则需要使用JSON.parseArray(String text, Class clazz)方法

猜你喜欢

转载自blog.csdn.net/qq_34577234/article/details/125199552