Fastjson使用
Fastjson介绍
官方主页:http://code.alibabatech.com/wiki/display/FastJSON/Home-zh
Fastjson是一个Java语言编写的JSON处理器。
1、遵循http://json.org标准,为其官方网站收录的参考实现之一。
2、支持JDK的各种类型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。
3、无依赖,不需要例外额外的jar,能够直接跑在JDK上。
source 下载
http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4.jarhttp://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4-sources.jar
使用
pom.xml文件中加入依赖依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency>
基本序列化
序列化就是把JavaBean对象转化成JSON格式的文本。
Object o = ...; String text = JSON.toJSONString(o);
在这个例子中,调用JSON.toJSONString方法,把对象o转化为JSON格式的文本。
使用@JSONField Annotation
在某些场景,你可能需要定制序列化输出,比如说,希望序列化采用之后采用“USERID”,而不是“id”,使用@JSONField这个Annotation。
public class User { @JSONField(name="USERID") public int getId() { ... } } User user = ...; JSON.toJSONString(user); // {"USERID":234}
序列化时过滤某些字段
方式一:使用@JSONField(serialize = false)
public class User { @JSONField(serialize = false) public int getId() { ... } } User user = ...;
方式二:在序列化时添加filter指定要序列化的字段,更面例子,指定序列化NewsEntity的id,pubTime,content,commentList这四个属性。
NewsEntity newsEntity = ...... SimplePropertyPreFilter filter = new SimplePropertyPreFilter(NewsEntity.class, "id","pubTime","content","commentList"); return JSON.toJSONString(new DetailModel("00", newsEntity), filter);
序列化时日期格式化
使用@JSONField (format=“yyyy-MM-dd HH:mm:ss”)指定日期属性格式
public class User { private Timestamp pubTime; @JSONField (format="yyyy-MM-dd HH:mm:ss") public Timestamp getPubTime() { return pubTime; } public void setPubTime(Timestamp pubTime) { this.pubTime = pubTime; } } User user = ...;
反序列化
反序列化就是把JSON格式的文本转化为Java Bean对象。
指定Class信息反序列化
通过指定类型信息,可以很方便的将“JSON文本”反序列化为“Java Bean”对象,例如:
String text = ...; // {"r":255,"g":0,"b":0,"alpha":255} Color color = JSON.parseObject(text, Color.class);
类型集合的反序列化
这个接口类似于parseObject
String text = ...; // [{ ... }, { ... }] List<User> users = JSON.parseArray(text, User.class);
泛型的反序列化
如果你需要返回一个带泛型的对象,例如List<User>、Map<String, User>,你可以使用TypeReference来传入类型信息。
String text = ...; // {"name":{"name":"ljw",age:18}} Map<String, User> userMap = JSON.parseObject(text, new TypeReference<Map<String, User>>() {});
组合类型集合的反序列化
比如在网络协议中,经常会存在这样的组合: [{/*header*/}, {/*body*/}]
fastjson对这种结构的反序列化有专门支持。
String text = ...; // [{/* header */}, {/* body */}] Type[] types = new Type[] {Header.class, Body.class}; List<Object> list = JSON.parseArray(text, types); Header header = (Header) list.get(0); Body body = (Body) list.get(1);