fastjson SerializerFeature詳解


依賴

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>

SerializerFeature屬性

名稱 含義 備注
QuoteFieldNames 輸出key時是否使用雙引號,默認為true  
UseSingleQuotes 使用單引號而不是雙引號,默認為false  
WriteMapNullValue 是否輸出值為null的字段,默認為false  
WriteEnumUsingToString Enum輸出name()或者original,默認為false  
UseISO8601DateFormat Date使用ISO8601格式輸出,默認為false  
WriteNullListAsEmpty List字段如果為null,輸出為[],而非null  
WriteNullStringAsEmpty 字符類型字段如果為null,輸出為”“,而非null  
WriteNullNumberAsZero 數值字段如果為null,輸出為0,而非null  
WriteNullBooleanAsFalse Boolean字段如果為null,輸出為false,而非null  
SkipTransientField 如果是true,類中的Get方法對應的Field是transient,序列化時將會被忽略。默認為true  
SortField 按字段名稱排序后輸出。默認為false  
WriteTabAsSpecial 把\t做轉義輸出,默認為false 不推薦
PrettyFormat 結果是否格式化,默認為false  
WriteClassName 序列化時寫入類型信息,默認為false。反序列化是需用到  
DisableCircularReferenceDetect 消除對同一對象循環引用的問題,默認為false  
WriteSlashAsSpecial 對斜杠’/’進行轉義  
BrowserCompatible 將中文都會序列化為\uXXXX格式,字節數會多一些,但是能兼容IE 6,默認為false  
WriteDateUseDateFormat 全局修改日期格式,默認為false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);  
DisableCheckSpecialChar 一個對象的字符串屬性中如果有特殊字符如雙引號,將會在轉成json時帶有反斜杠轉移符。如果不需要轉義,可以使用這個屬性。默認為false  
NotWriteRootClassName 含義  
BeanToArray 將對象轉為array輸出  
WriteNonStringKeyAsString 含義  
NotWriteDefaultValue 含義  
BrowserSecure 含義  
IgnoreNonFieldGetter 含義  
WriteEnumUsingName 含義  

示例

准備

  • User、Word來模擬各種數據類型。
  • SerializerFeatureTest:JSON部分示例的示例方法。

User類型:缺省get、set方法

public class User {

    private int id;
    private String name;
    private String add;
    private String old;
    }

Word類型:缺省get、set方法

public class Word {

    private String d;
    private String e;
    private String f;
    private String a;
    private int b;
    private boolean c;
    private Date date;
    private Map<String , Object> map;
    private List<User> list;
    }

SerializerFeatureTest:測試類

public class SerializerFeatureTest {

    private static Word word;

    private static void init() {
        word = new Word();
        word.setA("a");
        word.setB(2);
        word.setC(true);
        word.setD("d");
        word.setE("");
        word.setF(null);
        word.setDate(new Date());

        List<User> list = new ArrayList<User>();
        User user1 = new User();
        user1.setId(1);
        user1.setOld("11");
        user1.setName("用戶1");
        user1.setAdd("北京");
        User user2 = new User();
        user2.setId(2);
        user2.setOld("22");
        user2.setName("用戶2");
        user2.setAdd("上海");
        User user3 = new User();
        user3.setId(3);
        user3.setOld("33");
        user3.setName("用戶3");
        user3.setAdd("廣州");

        list.add(user3);
        list.add(user2);
        list.add(null);
        list.add(user1);

        word.setList(list);

        Map<String , Object> map = new HashedMap();
        map.put("mapa", "mapa");
        map.put("mapo", "mapo");
        map.put("mapz", "mapz");
        map.put("user1", user1);
        map.put("user3", user3);
        map.put("user4", null);
        map.put("list", list);
        word.setMap(map);
    }

    public static void main(String[] args) {
        init();
//        useSingleQuotes();
//        writeMapNullValue();
//        useISO8601DateFormat();
//        writeNullListAsEmpty();
//        writeNullStringAsEmpty();
//        sortField();
//        prettyFormat();
//        writeDateUseDateFormat();
//        beanToArray();
        showJsonBySelf();
    }

    /**
     * 9:自定義
     * 格式化輸出
     * 顯示值為null的字段
     * 將為null的字段值顯示為""
     * DisableCircularReferenceDetect:消除循環引用
     */
    private static void showJsonBySelf() {
        System.out.println(JSON.toJSONString(word));
        System.out.println(JSON.toJSONString(word, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty));
    }

    /**
     * 8:
     * 將對象轉為array輸出
     */
    private static void beanToArray() {
        word.setMap(null);
        word.setList(null);
        System.out.println(JSON.toJSONString(word));
        System.out.println(JSON.toJSONString(word, SerializerFeature.BeanToArray));
    }

    /**
     * 7:
     * WriteDateUseDateFormat:全局修改日期格式,默認為false。
     */
    private static void writeDateUseDateFormat() {
        word.setMap(null);
        word.setList(null);
        System.out.println(JSON.toJSONString(word));
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
        System.out.println(JSON.toJSONString(word, SerializerFeature.WriteDateUseDateFormat));
    }

    /**
     * 6:
     * PrettyFormat
     */
    private static void prettyFormat() {
        word.setMap(null);
        word.setList(null);
        System.out.println(JSON.toJSONString(word));
        System.out.println(JSON.toJSONString(word, SerializerFeature.PrettyFormat));
    }

    /**
     * SortField:按字段名稱排序后輸出。默認為false
     * 這里使用的是fastjson:為了更好使用sort field martch優化算法提升parser的性能,fastjson序列化的時候,
     * 缺省把SerializerFeature.SortField特性打開了。
     * 反序列化的時候也缺省把SortFeidFastMatch的選項打開了。
     * 這樣,如果你用fastjson序列化的文本,輸出的結果是按照fieldName排序輸出的,parser時也能利用這個順序進行優化讀取。
     * 這種情況下,parser能夠獲得非常好的性能。
     */
    private static void sortField() {
        System.out.println(JSON.toJSONString(word));
        System.out.println(JSON.toJSONString(word, SerializerFeature.SortField));
    }

    /**
     *  5:
     *  WriteNullStringAsEmpty:字符類型字段如果為null,輸出為"",而非null
     *  需要配合WriteMapNullValue使用,現將null輸出
     */
    private static void writeNullStringAsEmpty() {
        word.setE(null);
        System.out.println(JSONObject.toJSONString(word));
        System.out.println("設置WriteMapNullValue后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue));
        System.out.println("設置WriteMapNullValue、WriteNullStringAsEmpty后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty));
    }


    /**
     * 4:
     * WriteNullListAsEmpty:List字段如果為null,輸出為[],而非null
     * 需要配合WriteMapNullValue使用,現將null輸出
     */
    private static void writeNullListAsEmpty() {
        word.setList(null);
        System.out.println(JSONObject.toJSONString(word));
        System.out.println("設置WriteNullListAsEmpty后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty));
    }

    /**
     * 3:
     * UseISO8601DateFormat:Date使用ISO8601格式輸出,默認為false
     */
    private static void useISO8601DateFormat() {
        System.out.println(JSONObject.toJSONString(word));
        System.out.println("設置UseISO8601DateFormat后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.UseISO8601DateFormat));
    }

    /**
     * 2:
     * WriteMapNullValue:是否輸出值為null的字段,默認為false
     */
    private static void writeMapNullValue() {
        System.out.println(JSONObject.toJSONString(word));
        System.out.println("設置WriteMapNullValue后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 1:
     * UseSingleQuotes:使用單引號而不是雙引號,默認為false
     */
    private static void useSingleQuotes() {
        System.out.println(JSONObject.toJSONString(word));
        System.out.println("設置useSingleQuotes后:");
        System.out.println(JSONObject.toJSONString(word, SerializerFeature.UseSingleQuotes));
    }
}

對應輸出結果如下:

  • 1、useSingleQuotes:

     這里寫圖片描述
  •  2、writeMapNullValue:

       這里寫圖片描述

  • 3、useISO8601DateFormat: 

     這里寫圖片描述

  • 4、writeNullListAsEmpty:

      這里寫圖片描述

  • 5、writeNullStringAsEmpty: 

    這里寫圖片描述

  • 6、prettyFormat:
     
    這里寫圖片描述

  • 7、writeDateUseDateFormat: 

    這里寫圖片描述

  • 8、beanToArray:
     
    這里寫圖片描述

  • 9、自定義組合:showJsonBySelf: 

    這里寫圖片描述

 此時完整的輸出如下:

 

{"a":"a","b":2,"c":true,"d":"d","date":1473839656840,"e":"","list":[{"add":"廣州","id":3,"name":"用戶3","old":"33"},{"add":"上海","id":2,"name":"用戶2","old":"22"},null,{"add":"北京","id":1,"name":"用戶1","old":"11"}],"map":{"list":[{"$ref":"$.list[0]"},{"$ref":"$.list[1]"},null,{"$ref":"$.list[3]"}],"user3":{"$ref":"$.list[0]"},"mapz":"mapz","mapo":"mapo","mapa":"mapa","user1":{"$ref":"$.list[3]"}}}
{
    "a":"a",
    "b":2,
    "c":true,
    "d":"d",
    "date":1473839656840,
    "e":"",
    "f":"",
    "list":[
        {
            "add":"廣州",
            "id":3,
            "name":"用戶3",
            "old":"33"
        },
        {
            "add":"上海",
            "id":2,
            "name":"用戶2",
            "old":"22"
        },
        null,
        {
            "add":"北京",
            "id":1,
            "name":"用戶1",
            "old":"11"
        }
    ],
    "map":{
        "list":[
            {
                "add":"廣州",
                "id":3,
                "name":"用戶3",
                "old":"33"
            },
            {
                "add":"上海",
                "id":2,
                "name":"用戶2",
                "old":"22"
            },
            null,
            {
                "add":"北京",
                "id":1,
                "name":"用戶1",
                "old":"11"
            }
        ],
        "user4":null,
        "user3":{
            "add":"廣州",
            "id":3,
            "name":"用戶3",
            "old":"33"
        },
        "mapz":"mapz",
        "mapo":"mapo",
        "mapa":"mapa",
        "user1":{
            "add":"北京",
            "id":1,
            "name":"用戶1",
            "old":"11"
        }
    }
}

注意: 
fastjson把對象轉化成json避免$ref

學習地址: 
http://blog.csdn.net/glarystar/article/details/6654494 
http://blog.csdn.net/u013163567/article/details/50736096

項目github地址: 
https://github.com/gubaijin/buildmavenweb

 

-轉自:http://blog.csdn.net/u010246789/article/details/52539576


免責聲明!

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



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