fastjson 是阿里的开源项目,具网上的说法 fastjson 的解析速度是 Gson 的6倍,体积小,而且开源。
项目地址:
https://github.com/alibaba/fastjson
一般 json 解析器我们都用到的是序列化和反序列化。
- JSON.toJSONString
- parseObject。
下面举个例子来看看 fastjson 的具体用法:
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; } }
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; } }
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);
上面的代码输入结果如下:
{"id":0,"name":"admin","users":[{"id":2,"name":"guest"},{"id":3,"name":"root"}]}
反序列化操作如下:
Group group = JSON.parseObject(jsonString, Group.class);
时间: 2024-12-20 10:45:29