一、使用方式
FastJson
SerializeConfig serializeConfig=new SerializeConfig();
aserializeConfig.propertyNamingStrategy= PropertyNamingStrategy.SnakeCase;
String json = JSON.toJSONString(object, serializeConfig);
Jackson
ObjectMapper mapper=new ObjectMapper();
mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
String json = mapper.writeValueAsString(object);
Gson
GsonBuilder gsonBuilder=new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson=gsonBuilder.create();
String json = gson.toJson(object);
二、性能对比
**结论:**FastJson 约等于 Jackson > Gson
FastJson与Jackson性能相差不大,在大量数据测试下,Gson性能较差
对一个拥有11个字段的对象测试(仅供参考):
-
在循环9999次转换时,耗费时间
- FastJson 108ms
- Jackson 53ms
- Gson 73ms
-
在循环999999次转换时,耗费时间
- FastJson 448ms
- Jackson 1138ms
- Gson 332ms
-
在循环99999999次转换时,耗费时间
- FastJson 20418ms
- Jackson 28276ms
- Gson 70443ms
三、效果对比
打印json字符串
FastJson
仅转换有值的key-value,java.util.Date将被转换为时间戳
例:
{
"c_time":1615261985022,
"data_id":123,
"conf":{
"desc":"HaH_a",
"type":"set"
},
"remarks":"ReReRe"
}
Jackson
无值的key也会被转换,对象默认值为null
例:
{
"id":null,
"data_id":123,
"remarks":"ReReRe",
"status":null,
"c_time":1615261985022,
"u_time":null,
"conf":{
"key":null,
"type":"set",
"desc":"HaH_a"
}
Gson
仅转换有值的key-value,java.util.Date将被以字符串形式保存
例:
{
"data_id":123,
"remarks":"ReReRe",
"c_time":"Mar 9, 2021 11:53:05 AM",
"conf":{
"type":"set",
"desc":"HaH_a"
}
}