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

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

相关推荐
不辉放弃29 分钟前
java连数据库
java·mysql
jiet_h34 分钟前
Android锁
android
Hfc.6 小时前
docker-daemon.json
docker·容器·json
熊大如如8 小时前
Java 反射
java·开发语言
猿来入此小猿8 小时前
基于SSM实现的健身房系统功能实现十六
java·毕业设计·ssm·毕业源码·免费学习·猿来入此·健身平台
teacher伟大光荣且正确9 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
goTsHgo9 小时前
Spring Boot 自动装配原理详解
java·spring boot
卑微的Coder9 小时前
JMeter同步定时器 模拟多用户并发访问场景
java·jmeter·压力测试
pjx9879 小时前
微服务的“导航系统”:使用Spring Cloud Eureka实现服务注册与发现
java·spring cloud·微服务·eureka
多多*10 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle