maven中央仓库: http://central.maven.org/maven2/com/alibaba/fastjson/
Sourceforge.net : https://sourceforge.net/projects/fastjson/files/
在maven中如何配置fastjson依赖 fastjson最新版本都会发布到maven中央仓库,你可以直接依赖。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.55.android</version>
</dependency>
常用接口
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>>() {});
Demo
序列化:
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.addUser(guestUser);
group.addUser(rootUser);
String jsonString = JSON.toJSONString(group);
System.out.println(jsonString);
反序列化:
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;
}
public void addUser(User user) {
users.add(user);
}
}
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;
}
}