fastjson null 值轉換爲空字符串 key值統一大小寫

fastjson  可以設置 null值 轉爲 

SerializerFeature.WriteNullStringAsEmpty

但是這個屬性只針對實體,對 map這種結構不起效

此時需要如下所示,會將全部的null值轉換爲空字符串

但是特別注意,null值的時候丟失了原數據類型,所以不管數字,日期,或者其他的都變成了""

所以如果有可能還是不要偷懶,儘量用實體

  /*
        map值過濾爲"",以下的配置只針對實體起效
        SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty*/
    public void valuefilter(){
        Map<String,Object> map=new HashMap<>();
        map.put("name",null);
        map.put("sex","男");
        map.put("age",12);
        map.put("ECUCATION",12);
        map.put("people","漢");
        map.put("ti",null);
        ValueFilter filter = new ValueFilter() {
            @Override
            public Object process(Object obj, String s, Object v) {
                if(v==null)
                    return "";
                return v;
            }
        };
        System.out.println(JSONObject.toJSONString(map,filter
                ,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty));
    }

    /*
        map的key值統一爲小寫,以下的配置只針對實體起效
        SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty*/
    public void namefilter(){
        Map<String,Object> map=new HashMap<>();
        map.put("name",null);
        map.put("sex","男");
        map.put("age",12);
        map.put("ECUCATION",12);
        map.put("people","漢");
        map.put("ti",null);
        NameFilter filter = new NameFilter() {
            @Override
            public String process(Object obj, String s, Object v) {
                return s.toLowerCase();
            }
        };
        System.out.println(JSONObject.toJSONString(map,filter
                ,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty));
    }

    public static void main(String[] args) {
        FastJsonTest fastJsonTest=new FastJsonTest();
        //fastJsonTest.valuefilter();
        fastJsonTest.namefilter();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章