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

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


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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值