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);
指定转换的格式即可,
由于这个转换规则时可变参数,既可以指定多个规则。

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

相关推荐
best_virtuoso13 分钟前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
yudiandian201413 分钟前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
雨白40 分钟前
优雅地处理协程:取消机制深度剖析
android·kotlin
楚韵天工1 小时前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
helloworddm1 小时前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
失散131 小时前
分布式专题——43 ElasticSearch概述
java·分布式·elasticsearch·架构
ajsbxi1 小时前
【Java 基础】核心知识点梳理
java·开发语言·笔记
leon_zeng01 小时前
更改 Android 应用 ID (ApplicationId) 后遭遇记
android·发布
聪明的笨猪猪1 小时前
Java JVM “调优” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
重整旗鼓~2 小时前
28.redisson源码分析分布式锁
java·开发语言