说起Json 解析,有非常多方法,不管是出自Google 的Gson也好,还是来自其它的某某。想必大家都非常熟悉。
今日在github上闲逛。偶遇 一 json 解析库。看起来非常不错,据说是眼下最快的解析JOSN 方案。该东东为何神器,他就是来自于阿里团队的 fastjson.
为了方便起见,參考例如以下代码。
用maven 的同学就方便多了,直接双击打开你的pom.xml 文件,加入例如以下依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.36</version>
</dependency>
构建一下就OK了。
以下来详细看看:
ENCODE:
import com.alibaba.fastjson.JSON;
Group group = new Group();
group.setId(0L);
group.setName("admin");
User guestUser = new User();
guestUser.setId(2L);
guestUser.setName("guest");
User rootUser = new User();
rootUser.setId(3L);
rootUser.setName("root");
group.getUsers().add(guestUser);
group.getUsers().add(rootUser);
String jsonString = JSON.toJSONString(group);
System.out.println(jsonString);
OUTPUT:
{"id":0,"name":"admin","users":[{"id":2,"name":"guest"},{"id":3,"name":"root"}]}
DECODE:
String jsonString = ...;
Group group = JSON.parseObject(jsonString, Group.class);
Group.java
public class Group {
private Long id;
private String name;
private List<User> users = new ArrayList<User>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
User.java
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
很好用!
很多其它详情參考:https://github.com/alibaba/fastjson