为什么fastjson字段为null时不输出空字符串?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

为什么fastjson字段为null时不输出空字符串?

2016-03-09 18:31:25 5520 1
Map < String , Object > jsonMap = new HashMap< String , Object>();  
jsonMap.put("a",1);  
jsonMap.put("b","");  
jsonMap.put("c",null);  
jsonMap.put("d","wuzhuti.cn");  
  
String str = JSONObject.toJSONString(jsonMap);  
System.out.println(str);  
//输出结果:{"a":1,"b":"",d:"wuzhuti.cn"}  

从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性

也就是这个方法:JSONObject.toJSONString(Object object, SerializerFeature... features)
SerializerFeature有用的一些枚举值
`QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null`
现在加上
`Map < String , Object > jsonMap = new HashMap< String , Object>();
jsonMap.put("a",1);
jsonMap.put("b","");
jsonMap.put("c",null);
jsonMap.put("d","wuzhuti.cn");
String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);
System.out.println(str);
//输出结果:{"a":1,"b":"","c":null,"d":"wuzhuti.cn"} `
但是,如果把WriteNullStringAsEmpty也加进去,为什么不起作用?

String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);  
System.out.println(str);  
//输出结果:{"a":1,"b":"","c":null,"d":"wuzhuti.cn"}  

目前的解决办法是加一个过滤器

private ValueFilter filter = new ValueFilter() {
    @Override
    public Object process(Object obj, String s, Object v) {
    if(v==null)
        return "";
    return v;
    }
};
JSON.toJSONString(jsonMap, filter)
取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 18:56:32

    对规则的理解:

    1.SerializerFeature.WriteMapNullValue 是否输出值为null的字段,默认为false
    也就是说有null时会输出而不是忽略(默认策略是忽略,所以看不到为null的字段)
    2.WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
    注意是字段是字段是字段,而不是json.put("key",null),所以用它时,字段为null的可以转换为空字符串。
    3.如果让输出的json中所有为null的字符串都变成空字符串,最简单的做法就是加一个值过滤器,这样就避免了有的字段为null,有的字段为空字符的现象。
    贴点示例代码:

    public class Demo1 {
    
        public class Student {
            private String name;
            private int age;
            private boolean isMale;
            private Student gf;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public int getAge() {
                return age;
            }
    
            public void setAge(int age) {
                this.age = age;
            }
    
            public boolean isMale() {
                return isMale;
            }
    
            public void setMale(boolean isMale) {
                this.isMale = isMale;
            }
    
            public Student getGf() {
                return gf;
            }
    
            public void setGf(Student gf) {
                this.gf = gf;
            }
        }
    
        private static ValueFilter filter = new ValueFilter() {
            @Override
            public Object process(Object obj, String s, Object v) {
                if (v == null)
                    return "";
                return v;
            }
        };
    
        public static void main(String[] args) {
            new Demo1().foo();
            new Demo1().bar();
        }
    
        private void foo() {
            System.out.println("foo()---------------------------");
            JSONObject j1 = new JSONObject();
            j1.put("name", "zhangsan");
            j1.put("age", 13);
            j1.put("isMale", true);
            j1.put("gf", null);
            Map<String, Object> fav = new HashMap<String, Object>();
            Set<String> books = new HashSet<String>();
            books.add("三国");
            books.add("史记");
            fav.put("history", books);
            String[] arts = new String[] {};
            fav.put("arts", arts);
            String[] musics = new String[] { "北京欢迎你", "画心" };
            fav.put("musics", musics);
            List<String> sports = new ArrayList<String>();
            fav.put("sports", sports);
            j1.put("fav", fav);
            List<Student> classmates = new ArrayList<Student>();
            classmates.add(new Student());
            Student lisi = new Student();
            lisi.setMale(false);
            lisi.setAge(11);
            classmates.add(lisi);
            Student zhangsan = new Student();
            zhangsan.setAge(13);
            zhangsan.setName("张三");
            zhangsan.setMale(true);
            zhangsan.setGf(lisi);
            classmates.add(zhangsan);
            j1.put("classmates", classmates);
            String str = null;
            j1.put("str", str);
            System.out.println(j1.toString());
            System.out
                .println(JSON.toJSONString(j1, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(
                JSON.toJSONString(j1, filter, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(JSON.toJSONString(j1, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(JSON.toJSONString(j1, filter, SerializerFeature.WriteNullStringAsEmpty));
    
            Map<String, JSONObject> m = new HashMap<String, JSONObject>();
            m.put("key", j1);
            System.out.println(
                JSON.toJSONString(m, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(JSON.toJSONString(m, filter, SerializerFeature.WriteNonStringKeyAsString,
                SerializerFeature.WriteNullStringAsEmpty));
    
        }
    
        private void bar() {
            System.out.println("bar()---------------------------");
            Student zhangsan = new Student();
            zhangsan.setAge(13);
            zhangsan.setName("张三");
            zhangsan.setMale(true);
            Student lisi = new Student();
            // lisi.setName("lisi");
            lisi.setMale(false);
            lisi.setAge(11);
            zhangsan.setGf(lisi);
            System.out.println(
                JSON.toJSONString(zhangsan, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(JSON.toJSONString(zhangsan, SerializerFeature.WriteMapNullValue));
            System.out.println(JSON.toJSONString(zhangsan, SerializerFeature.WriteNullStringAsEmpty));
            System.out.println(JSON.toJSONString(zhangsan));
            System.out.println(JSON.toJSONString(zhangsan, filter));
            System.out.println(JSON.toJSONString(zhangsan, filter, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty));
        }
    }

    输出结果:
    `foo()---------------------------
    {"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}
    {"str":null,"isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":null,"male":false,"name":""},{"age":11,"gf":null,"male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":null}
    {"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}
    {"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}
    {"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}
    {"key":{"isMale":true,"name":"zhangsan","classmates":[{"age":0,"male":false},{"age":11,"male":false},{"age":13,"gf":{"$ref":"$.key.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13}}
    {"key":{"str":"","isMale":true,"name":"zhangsan","classmates":[{"age":0,"gf":"","male":false,"name":""},{"age":11,"gf":"","male":false,"name":""},{"age":13,"gf":{"$ref":"$.key.classmates[1]"},"male":true,"name":"张三"}],"fav":{"sports":[],"musics":["北京欢迎你","画心"],"history":["史记","三国"],"arts":[]},"age":13,"gf":""}}
    bar()---------------------------
    {"age":13,"gf":{"age":11,"gf":null,"male":false,"name":""},"male":true,"name":"张三"}
    {"age":13,"gf":{"age":11,"gf":null,"male":false,"name":null},"male":true,"name":"张三"}
    {"age":13,"gf":{"age":11,"male":false},"male":true,"name":"张三"}
    {"age":13,"gf":{"age":11,"male":false},"male":true,"name":"张三"}
    {"age":13,"gf":{"age":11,"gf":"","male":false,"name":""},"male":true,"name":"张三"}
    {"age":13,"gf":{"age":11,"gf":"","male":false,"name":""},"male":true,"name":"张三"}`

    0 0
相关问答

37

回答

阿里官方Java代码规范标准《阿里巴巴Java开发手册》下载

管理贝贝 2017-02-10 15:14:36 77744浏览量 回答数 37

2

回答

[@徐雷frank][¥20]在用fastjson将字符串转为JSONObject对象时,double类型被转为BigDecimal类型

jiang0512 2018-11-23 15:15:21 7050浏览量 回答数 2

1

回答

@ResponseBody与response.getWriter .write()区别

蛮大人123 2016-02-22 11:11:38 5140浏览量 回答数 1

2

回答

赛题一:《人机行为识别》大家写udf的时候是什么提取json数据啊

cj753733 2017-02-15 20:04:39 4690浏览量 回答数 2

2

回答

1.2.7版本fastjson转字符串后key的排序,如何能完全按字母顺序排列?

杨冬芳 2016-07-07 16:13:51 6905浏览量 回答数 2

1

回答

alibaba fastjson将json串转成对象时没有空构造器会报错

echo2019 2018-07-11 14:44:39 3290浏览量 回答数 1

2

回答

建议将aliyun-sdk-oss依赖的json-lib改成fastjson

咸鸭蛋 2015-11-30 16:43:48 6557浏览量 回答数 2

2

回答

Redis存放java对象为何序列化?

落地花开啦 2016-02-20 15:07:44 8143浏览量 回答数 2

1

回答

fastjson在反序列化时怎么解析对象中的继承

蛮大人123 2016-02-28 14:02:57 4595浏览量 回答数 1

1

回答

fastJson如何将json字符串转为list<javaBean>

杨冬芳 2016-07-06 14:25:43 5189浏览量 回答数 1
+关注
蛮大人123
我说我不帅他们就打我,还说我虚伪
0
文章
7733
问答
问答排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载