使用fastjson,gson解析null值的時候鍵保留


由於業務需求。。。所以查閱資料,總結如下:

使用gson實現方法:只需要把new Gson()改為:

new GsonBuilder().serializeNulls().create(); 就可以了
復制代碼
public class Test {
    public static void main(String[] args) {
        Gson gson= new GsonBuilder().serializeNulls().create();
        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 = gson.toJson(jsonMap);
        System.out.println(str);
        
        person peson1 = new person();
        peson1.setAge(1);
        peson1.setName(null);
        System.out.println(gson.toJson(peson1));
    }
    
}
class person{
    private int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}
復制代碼

使用fastjson實現方法:只需要再toJsonString的時候加上

SerializerFeature.WriteMapNullValue 這個參數。
復制代碼
public class FastJsonTest {
    public static void main(String[] args) {
        /*
         * 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", "json");
 
        String str = JSONObject.toJSONString(jsonMap);
        // 忽略null輸出
        System.out.println(str);
 
        String str2 = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);

        System.out.println(str2);
 
        String json = "{\"fail\":null,\"updateTimestamp\":\"1484096131863\",\"productName\":\"json測試\"}";
        // 忽略null輸出
        System.out.println(JSON.parse(json));
        // 
        System.out.println(JSONObject.toJSON(json));
    }
 
}
復制代碼

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM