这里介绍 fastjson 用于生成和解析 JSON 数据的简单示例
1、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; } }
2、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; } }3、Java代码
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);
4、输出结果
{ "name":"admin","id":0,"users":[ {"name":"guest","id":2},{"name":"root","id":3} ] }
5、解析
Group group2 = JSON.parSEObject(jsonString,Group.class);原文:http://www.oschina.net/code/snippet_12_3495