利用fastjson序列化对象为JSON
参考博客:http://blog.csdn.net/zeuskingzb/article/details/17468079
Step1:定义实体类
//用户类
public class User {
private Long id;
private String name;
//增加get/set方法
}
//定义组,1组有多个用户
public class Group {
private Long id;
private String name;
private List<User> users = new ArrayList<User>(); //增加get/set方法
}
Step2:定义测试类,将实体对象转换成JSON格式输出
//测试类
public class Test {
public static void main(String[] args) {
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);
Group group2 = JSON.parseObject(jsonString, Group.class);//将json反序列化为对象
} }
输出结果:
{"id":0,"name":"admin","users":[{"id":2,"name":"guest"},{"id":3,"name":"root"}]}