fastjson 基本使用方法

前端之家收集整理的这篇文章主要介绍了fastjson 基本使用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这里介绍 fastjson 用于生成和解析 JSON 数据的简单示例

1、Java代码

  1. public class User {
  2. private Long id;
  3. private String name;
  4.  
  5. public Long getId() { return id; }
  6. public void setId(Long id) { this.id = id; }
  7.  
  8. public String getName() { return name; }
  9. public void setName(String name) { this.name = name; }
  10. }

2、Java代码
  1. public class Group {
  2. private Long id;
  3. private String name;
  4. private List<User> users = new ArrayList<User>();
  5.  
  6. public Long getId() { return id; }
  7. public void setId(Long id) { this.id = id; }
  8.  
  9. 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. }
3、Java代码
  1. import com.alibaba.fastjson.JSON;
  2.  
  3. Group group = new Group();
  4. group.setId(0L);
  5. group.setName("admin");
  6.  
  7. User guestUser = new User();
  8. guestUser.setId(2L);
  9. 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);

4、输出结果

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


5、解析
  1. Group group2 = JSON.parSEObject(jsonString,Group.class);
原文:http://www.oschina.net/code/snippet_12_3495

猜你在找的Json相关文章