转载于:http://code.alibabatech.com/wiki/display/FastJSON/Serial+Features
Fastjson序列化时,可以指定序列化的特性,以满足不同的序列化需求。
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));
System.out.println(JSON.toJSONString(date, SerializerFeature.UseISO8601DateFormat));
SerializerFeature[] features = {SerializerFeature.UseISO8601DateFormat, SerializerFeature.UseSingleQuotes };
System.out.println(JSON.toJSONString(date, features));
|
详细说明表格
| Featurs | 缺省值 | 说明 |
| QuoteFieldNames |
true |
序列化输出字段,使用引号。例如: QuoteFieldNames Feature Enabled:
{"id":123,
"name":"张三",
"age":23}
|
QuoteFieldNames Feature Disabled:
{id:123,
name:"张三",
age:23}
|
|
| UseSingleQuotes |
false |
使用单引号而不是双引号 UseSingleQuotes Feature Enabled:
{'id':123,
'name':'张三',
'age':23}
|
UseSingleQuotes Feature Disabled:
{"id":123,
"name":"张三",
"age":23}
|
|
| WriteMapNullValue |
false |
空值是否输出。大多数情况,值为null的属性输出是没有意义的,缺省这个特性是打开的。 WriteMapNullValue Feature Enabled:
{'id':123,
'name':'张三',
'age':23,
birthday : null}
|
WriteMapNullValue Feature Disabled:
{"id":123,
"name":"张三",
"age":23}
|
|
| WriteEnumUsingToString |
false |
Enum输出name()或者original
public
static
enum
Type {
Big,
Medium, Small
}
System.out.println(JSON.toJSONString(Type.Big));
System.out.println(JSON.toJSONString(Type.Medium));
System.out.println(JSON.toJSONString(Type.Small));
System.out.println(JSON.toJSONString(Type.Big,
SerializerFeature.WriteEnumUsingToString));
System.out.println(JSON.toJSONString(Type.Medium,
SerializerFeature.WriteEnumUsingToString));
System.out.println(JSON.toJSONString(Type.Small,
SerializerFeature.WriteEnumUsingToString));
|
|
| UseISO8601DateFormat |
false |
Date使用ISO8601格式输出
Date
date = new
Date(1308841916550L);
System.out.println(JSON.toJSONString(date));
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做转义输出。 |