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

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

相关推荐
txxzjmzlh3 分钟前
Thread 类的基本用法
java·开发语言
好家伙VCC23 分钟前
**基于RISC-V架构的嵌入式系统开发:从零开始构建高效低功耗应用**在当前物联网(IoT)和边缘计
java·python·物联网·架构·risc-v
wyu7296134 分钟前
Spring框架学习笔记:从IoC到声明式事务
java
qqacj1 小时前
Spring Security 官网文档学习
java·学习·spring
Rsun045511 小时前
10、Java 桥接模式从入门到实战
java·开发语言·桥接模式
金銀銅鐵1 小时前
[Java] 从 class 文件看 cglib 对 MethodInterceptor 的处理 (下)
java·后端
lee_curry1 小时前
Java中关于“锁”的那些事
java·线程·并发·juc
pearlthriving1 小时前
c++当中的泛型思想以及c++11部分新特性
java·开发语言·c++
安卓程序员_谢伟光1 小时前
m3颜色定义
android·compose
梦魇星虹2 小时前
idea Cannot find declaration to go to
java·ide·intellij-idea