将Json字符串转对象时因为值为null而丢失键值或被过滤的问题
问题:使用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);
后序:主页有一篇针对这个问题的文章,希望有所帮助
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)