Fastjson2使用JSONOObject或者mao转换为JSON字符串时丢失Null值字段

最近在工作中发现问题fastJson转换为JSONString时丢失值为null的问题特此解决。

java 复制代码
public class test001 {

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("foo1", "bar");
        jsonObject.put("foo2", "baz");
        jsonObject.put("foo3", "");
        jsonObject.put("foo4", null);

        String jsonString = JSON.toJSONString(jsonObject);
        System.out.println(jsonString);
        /**
        *输出结果
         * {"foo1":"bar","foo2":"baz","foo3":""}
         */
//        JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty));
//        String str = JSON.toJSONString(jsonString, JSONWriter.Feature.WriteNullListAsEmpty);
//        System.out.println(str);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("foo1", new ArrayList<>());
        jsonObject1.put("", null);
        jsonObject1.put("foo3", "");
        jsonObject1.put("foo4", null);
        jsonObject1.put(null, "");
//        String str1= JSON.toJSONString(jsonObject1,JSONWriter.Feature.WriteNullListAsEmpty);
        String str2= JSON.toJSONString(jsonObject1,JSONWriter.Feature.WriteNulls);
//        System.out.println(str1);
        System.out.println(str2);
        /**
         *输出结果
         * {"foo1":[],"":"","foo3":"","foo4":null,"null":""}
         */

        String str3= JSON.toJSONString(jsonObject1);
//        System.out.println(str1);
        System.out.println(str3);
        /**
         *输出结果
         * {"foo1":[],"":"","foo3":"",null:""}
         */
        
    }
}

只需要在转换的后面加上

复制代码
String str2= JSON.toJSONString(jsonObject1,JSONWriter.Feature.WriteNulls);
指定转换的格式即可,
由于这个转换规则时可变参数,既可以指定多个规则。

以下格式不在讲述自己可以尝试代码

相关推荐
小屁孩大帅-杨一凡1 分钟前
如何解决ThreadLocal内存泄漏问题?
java·开发语言·jvm·算法
还是奇怪22 分钟前
Linux - 安全排查 3
android·linux·安全
学习3人组22 分钟前
在 IntelliJ IDEA 系列中phpstorm2025设置中文界面
java·ide·intellij-idea
Android采码蜂40 分钟前
BLASTBufferQueue03-BufferQueueConsumer核心操作
android
Android采码蜂1 小时前
BLASTBufferQueue02-BufferQueueProducer核心操作
android
2501_915921431 小时前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
android·ios·小程序·https·uni-app·iphone·webview
码农明明2 小时前
Google Play 应用上架二三事
android·google
cainiao0806052 小时前
Java 大视界:基于 Java 的大数据可视化在智慧城市能源消耗动态监测与优化决策中的应用(2025 实战全景)
java
长风破浪会有时呀2 小时前
记一次接口优化历程 CountDownLatch
java
云朵大王3 小时前
SQL 视图与事务知识点详解及练习题
java·大数据·数据库