var
来源:景安资讯平台作者:小韩发布时间:2016-02-17点击:1838
最近不少人都在问我关于fastjson的相关问题,今天这里介绍 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. [代码]编码
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);
版权声明:本文系技术人员研究整理的智慧结晶,转载勿用于商业用途,并保留本文链接,侵权必究!