Fastjson Feathure

轉載於:http://code.alibabatech.com/wiki/display/FastJSON/Serial+Featuresjava

Fastjson序列化時,能夠指定序列化的特性,以知足不一樣的序列化需求。json

SerialFeature類的定義

package com.alibaba.fastjson.serializer;
 
public enum SerializerFeature {
     QuoteFieldNames, UseSingleQuotes, WriteMapNullValue, WriteEnumUsingToString, UseISO8601DateFormat, SkipTransientField
}

使用舉例

Date date = new Date(1308841916550L);
 
// 缺省輸出
System.out.println(JSON.toJSONString(date)); // 1308841916550
 
// 使用特性 UseISO8601DateFormat
// "2011-06-23T23:11:56.550"
System.out.println(JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat));
 
// 組合兩個Feature(UseISO8601DateFormat和UseSingleQuotes)輸出日期
SerializerFeature[] features = {SerializerFeature.UseISO8601DateFormat, SerializerFeature.UseSingleQuotes };
System.out.println(JSON.toJSONString(date, features)); // '2011-06-23T23:11:56.550'

詳細說明表格

Featurs 缺省值 說明
QuoteFieldNames true 序列化輸出字段,使用引號。例如:
QuoteFieldNames Feature Enabled:
{ "id" : 123 , "name" : "張三" , "age" : 23 }

QuoteFieldNames Feature Disabled:spa

{id: 123 , name: "張三" , age: 23 }
UseSingleQuotes false 使用單引號而不是雙引號
UseSingleQuotes Feature Enabled:
{ 'id' : 123 , 'name' : '張三' , 'age' : 23 }

UseSingleQuotes Feature Disabled:code

{ "id" : 123 , "name" : "張三" , "age" : 23 }
WriteMapNullValue false 空值是否輸出。大多數狀況,值爲null的屬性輸出是沒有意義的,缺省這個特性是打開的。
WriteMapNullValue Feature Enabled:
{ 'id' : 123 , 'name' : '張三' , 'age' : 23 , birthday : null }

WriteMapNullValue Feature Disabled:orm

{ "id" : 123 , "name" : "張三" , "age" : 23 }
WriteEnumUsingToString false Enum輸出name()或者original
public static enum Type {
     Big, Medium, Small
}
 
System.out.println(JSON.toJSONString(Type.Big)); // 0
System.out.println(JSON.toJSONString(Type.Medium)); // 1
System.out.println(JSON.toJSONString(Type.Small)); // 2
 
System.out.println(JSON.toJSONString(Type.Big, SerializerFeature.WriteEnumUsingToString)); // "Big"
System.out.println(JSON.toJSONString(Type.Medium, SerializerFeature.WriteEnumUsingToString)); // "Medium"
System.out.println(JSON.toJSONString(Type.Small, SerializerFeature.WriteEnumUsingToString)); // "Small"
UseISO8601DateFormat false Date使用ISO8601格式輸出
Date date = new Date(1308841916550L);
System.out.println(JSON.toJSONString(date)); // 1308841916550
 
// "2011-06-23T23:11:56.550"
System.out.println(JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat));
SkipTransientField true 若是是true,類中的Get方法對應的Field是transient,序列化時將會被忽略
WriteNullListAsEmpty false list字段若是爲null,輸出爲[],而不是null
WriteNullNumberAsZero false 數值字段若是爲null,輸出爲0,而不是null
WriteNullBooleanAsFalse false Boolean字段若是爲null,輸出爲false,而不是null
WriteNullStringAsEmpty false 字符類型字段若是爲null,輸出爲"",而不是null
SortField false 按字段名稱排序後輸出
WriteTabAsSpecial false 把\t作轉義輸出。
相關文章
相關標籤/搜索