問題:使用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);
后序:主頁有一篇針對這個問題的文章,希望有所幫助