將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);

后序:主頁有一篇針對這個問題的文章,希望有所幫助


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM