在面对一个业务逻辑中,某一个后端项目需要解析其他项目的response返回值使用JSONUtil.parseObj(response.getData());解析data数据,完成后想响应给前端却报
No serializer found for class cn.hutool.json.JSONNull and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: cn.hutool.json.JSONObject["list"]->cn.hutool.json.JSONArray[0]- >cn.hutool.json.JSONObject["checkRuleEndTime"])错误
复制
JSONUtil.parseObj默认不忽略错误,解析空字符串或 null 时返回空的 JSONObject。
JSONUtil.parseObj(jsonStr, true):忽略解析错误,解析空字符串或 null 时返回空的JSONObject,解析无效 JSON 字符串时也返回空的 JSONObject。
当修改完成以后,发现还是会报JSONNull错误。
JSONObject在底层是一个Map,当项目封装数据JSON时默认使用jackson包下的writeValueAsString方法,就会报JSONNull错误,另一个项目传过来的null并不会被识别为null,“null”字符串放到JSONObject类中时,取出来的使用会转换成net.sf.json.JSONNull类型,所以在进行writeValueAsString响应的时候就会报错。
解决办法:
全局配置解决,我们可以采用https://blog.csdn.net/JRocks/article/details/116533593 创建配置类形式。
局部解决:
如果不想全局应用会影响其他模块,我们可以采用更改类型方式
代码示例:
JSONObject jsonResponse = JSONUtil.parseObj(response.getData(), false); List<JSONObject> originalList = (List<JSONObject>)jsonResponse.remove("list"); List<RuleConsistencyVO> listVo = originalList.stream().map(item -> JSONUtil.toBean(item.toString(), RuleConsistencyVO.class)).collect(Collectors.toList()); PageInfo<RuleConsistencyVO> pageInfo = JSONUtil.toBean(jsonResponse.toString(),PageInfo.class); pageInfo.setList(listVo);
复制
这里我拿到了list下的数据,把原来list数据给remove了,通过JSONUtil.toBean的形式把JSONObject类型的数据转换成了实体类,再重新塞回去,这样就解决了。
这样在data中就不是JSONObject类型,而是我的自己的类型,在响应的时候就为null了。