当前位置: 代码迷 >> JavaScript >> fastjson 根本使用方法
  详细解决方案

fastjson 根本使用方法

热度:897   发布时间:2012-11-01 11:11:31.0
fastjson 基本使用方法

?fastjson 用于生成和解析 JSON 数据的简单示例

[代码] [Java]代码

01 public class User {
02 ????private Long id;
03 ????private String name;
04 ??
05 ????public Long getId() { return id; }
06 ????public void setId(Long id) { this.id = id; }
07 ??
08 ????public String getName() { return name; }
09 ????public void setName(String name) { this.name = name; }
10 }

[代码] [Java]代码

01 public class Group {
02 ????private Long id;
03 ????private String name;
04 ????private List<User> users = new ArrayList<User>();
05 ??
06 ????public Long getId() { return id; }
07 ????public void setId(Long id) { this.id = id; }
08 ??
09 ????public String getName() { return name; }
10 ????public void setName(String name) { this.name = name; }
11 ??
12 ????public List<User> getUsers() { return users; }
13 ????public void setUsers(List<User> users) { this.users = users; }
14 }

[代码] 编码

01 import com.alibaba.fastjson.JSON;
02 ??
03 Group group = new Group();
04 group.setId(0L);
05 group.setName("admin");
06 ??
07 User guestUser = new User();
08 guestUser.setId(2L);
09 guestUser.setName("guest");
10 ??
11 User rootUser = new User();
12 rootUser.setId(3L);
13 rootUser.setName("root");
14 ??
15 group.getUsers().add(guestUser);
16 group.getUsers().add(rootUser);
17 ??
18 String jsonString = JSON.toJSONString(group);
19 ??
20 System.out.println(jsonString);

[代码] 输出结果

1 {
2 ??????"name":"admin",
3 ??????"id":0,"users":[
4 ?????????????????????????????{"name":"guest","id":2},
5 ?????????????????????????????{"name":"root","id":3}
6 ?????????????????????????]
7 }

[代码] 解码

1 Group group2 = JSON.parseObject(jsonString, Group.class);
  相关解决方案