http://zhidao.baidu.com/link?url=buRL8gjIT75xDZgYJG7SwyB5EzES8cgiNPDCPLNMPXLVYyNR9tPbklmxOYWVzmTT0G1V1ewdcLmaTvTwnqTSF9ZS_hl8gC_Ed4iNdYD1XYu
看fastjson源码,SerializeWriter
public void writeEnum(Enum> value, char c) {
if (value == null) {
writeNull();
write(',');
return;
}
if (isEnabled(SerializerFeature.WriteEnumUsingToString)) {
if (isEnabled(SerializerFeature.UseSingleQuotes)) {
write('\'');
write(value.name());
write('\'');
write(c);
} else {
write('\"');
write(value.name());
write('\"');
write(c);
}
return;
}
writeIntAndChar(value.ordinal(), c);
}
public static int DEFAULT_GENERATE_FEATURE;
static {
int features = 0;
features |= com.alibaba.fastjson.serializer.SerializerFeature.QuoteFieldNames.getMask();
features |= com.alibaba.fastjson.serializer.SerializerFeature.SkipTransientField.getMask();
features |= com.alibaba.fastjson.serializer.SerializerFeature.WriteEnumUsingToString.getMask();
features |= com.alibaba.fastjson.serializer.SerializerFeature.SortField.getMask();
// features |=
// com.alibaba.fastjson.serializer.SerializerFeature.WriteSlashAsSpecial.getMask();
DEFAULT_GENERATE_FEATURE = features;
}
而且如果直接调用JSON.toJSON把实体类转为json,这里还有另外一句代码
if (clazz.isEnum()) {
return ((Enum>) javaObject).name();
}
再继续看fastjson的源码
在JOSN.toJSONString中
public static final String toJSONString(Object object, SerializerFeature... features) {
SerializeWriter out = new SerializeWriter();
try {
JSONSerializer serializer = new JSONSerializer(out);
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
serializer.config(feature, true);
}
serializer.write(object);
return out.toString();
} finally {
out.close();
}
}
他这里也是用的serializer.config来配置的,干脆我们自己写个工具方法吧,同时把WriteEnumUsingToString禁用掉
private static final SerializerFeature[] CONFIG = new SerializerFeature[]{
SerializerFeature.WriteNullBooleanAsFalse,//boolean为null时输出false
SerializerFeature.WriteMapNullValue, //输出空置的字段
SerializerFeature.WriteNonStringKeyAsString,//如果key不为String 则转换为String 比如Map的key为Integer
SerializerFeature.WriteNullListAsEmpty,//list为null时输出[]
SerializerFeature.WriteNullNumberAsZero,//number为null时输出0
SerializerFeature.WriteNullStringAsEmpty//String为null时输出""
};
public static JSONObject toJSON(Object javaObject) {
SerializeWriter out = new SerializeWriter();
String jsonStr;
try {
JSONSerializer serializer = new JSONSerializer(out);
for (com.alibaba.fastjson.serializer.SerializerFeature feature : CONFIG) {
serializer.config(feature, true);
}
serializer.config(SerializerFeature.WriteEnumUsingToString, false);
serializer.write(javaObject);
jsonStr = out.toString();
} finally {
out.close();
}
JSONObject jsonObject = JSON.parseObject(jsonStr);
return jsonObject;
}