程序员的资源宝库

网站首页 > gitee 正文

将Json字符串转对象时因为值为null而丢失键值或被过滤的问题

sanyeah 2024-04-12 17:38:04 gitee 4 ℃ 0 评论

问题:使用hutool的Json工具时,将Json转为object对象时,因为属性值存在null而导致转化后对象中整个键值丢失,现在要求,就算属性值为null,依然保留该属性。

出现的错误:

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class cn.hutool.json.JSONNull]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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: com.ruoyi.framework.web.domain.AjaxResult["data"]->cn.hutool.json.JSONObject["Content"]->cn.hutool.json.JSONObject["AcceptanceDistribution"]->cn.hutool.json.JSONObject["ChartSubTitle"])

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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: com.ruoyi.framework.web.domain.AjaxResult["data"]->cn.hutool.json.JSONObject["Content"]->cn.hutool.json.JSONObject["AcceptanceDistribution"]->cn.hutool.json.JSONObject["ChartSubTitle"])

错误代码:JSONObject res = JSONUtil.parseObj(data);

解决方式:JSONObject res = JSONUtil.parseObj(data, false);第二个参数意思是:忽略空值转换,默认为true,此处设置为false,就算是null也要转换显示出来。(此种方式不能保证所有情况都适用,可能出现不起作用的情况,如果无效可采用自定义config引入bean的方式或者改用fastJson,但是不推荐使用fastJson因为有很大的弊端)

注意:如果使用的是fastJson对象转Json字符串时,则是String res= JSONObject.toJSONString(object, SerializerFeatrue.WriteMapNullValue);

后序:主页有一篇针对这个问题的文章,希望有所帮助

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表