你可以通過如下地方下載fastjson:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.21</version>
</dependency>
android版本
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.55.android</version>
</dependency>
fastjson入口類是com.alibaba.fastjson.JSON,主要的API是JSON.toJSONString,和parseObject。
package com.alibaba.fastjson;
public abstract class JSON {
public static final String toJSONString(Object object);
public static final <T> T parseObject(String text, Class<T> clazz, Feature... features);
}
序列化:
String jsonString = JSON.toJSONString(obj);
反序列化:
VO vo = JSON.parseObject("...", VO.class);
泛型反序列化:
import com.alibaba.fastjson.TypeReference;
List<VO> list = JSON.parseObject("...", new TypeReference<List<VO>>() {});
fastjson的使用例子看這里:Samples-DataBind
fastjson是目前java語言中最快的json庫,比自稱最快的jackson速度要快,第三方獨立測試結(jié)果看這里:fastjson性能對比 。
自行做性能測試時,關(guān)閉循環(huán)引用檢測的功能。
JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect)
VO vo = JSON.parseObject("...", VO.class, Feature.DisableCircularReferenceDetect)
這里有jackson作者cowtowncoder等人對fastjson的性能評價:https://groups.google.com/forum/#!topic/java-serialization-benchmarking/8eS1KOquAhw
fastjson比gson快大約6倍,測試結(jié)果上這里:性能測試對比。gson的g可能是“龜”拼音的縮寫,龜速的json庫。
fastjson有專門的for android版本,去掉不常用的功能。jar占的字節(jié)數(shù)更小。git branch地址是:https://github.com/alibaba/fastjson/tree/android 。
不需要,fastjson的序列化和反序列化都不需要做特別配置,唯一的要求是,你序列化的類符合java bean規(guī)范。
fastjson處理日期的API很簡單,例如:
JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")
使用ISO-8601日期格式
JSON.toJSONString(obj, SerializerFeature.UseISO8601DateFormat);
全局修改日期格式
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd"; JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
反序列化能夠自動識別如下日期格式:
你可以使用SimplePrePropertyFilter過濾字段,詳細(xì)看這里:https://github.com/alibaba/fastjson/wiki/%E4%BD%BF%E7%94%A8SimplePropertyPreFilter%E8%BF%87%E6%BB%A4%E5%B1%9E%E6%80%A7
關(guān)于定制序列化,詳細(xì)的介紹看這里:Fastjson定制系列化
使用SerializerFeature.DisableCircularReferenceDetect特性關(guān)閉引用檢測和生成。例如:
String jsonString = JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
fastjson提供了BrowserCompatible這個配置,打開之后,所有的中文都會序列化為\uXXXX這種格式,字節(jié)數(shù)會多一些,但是能兼容IE 6。
String jsonString = JSON.toJSONString(obj, SerializerFeature.BrowserCompatible);
fastjson提供了Stream API,詳細(xì)看這里Fastjson Stream api
fastjson提供了使用Annotation定制序列化和反序列化的功能。Fastjson JSONField
更多建議: