fastjson 是alibaba的一個Json處理工具包。html
fastjson只須要掌握兩個靜態方法:JSON.toJSONString和JSON.parseObject java
fastjson示例:git
User.javagithub
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; } }
Group.javajson
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; } public void addUser(User user) { users.add(user); } }
EncodeTest.java工具
public class EncodeTest { public static void main(String[] args) { Group group = new Group(); group.setId(0L); group.setName("admin"); User u = new User(); u.setId(1L); u.setName("wangsan"); User li = new User(); li.setId(2L); li.setName("lisi"); group.addUser(u); group.addUser(li); String jsonString = JSON.toJSONString(group); System.out.println(jsonString); } }
輸出結果:{"id":0,"name":"admin","users":[{"id":1,"name":"wangsan"},{"id":2,"name":"lisi"}]}this
DecodeTest.javaspa
public class DecodeTest { public static void main(String[] args) { String jsonStr = "{‘id’:0,‘name’:‘admin’,‘users’:[{‘id’:1,‘name’:‘wangsan’},{‘id’:2,‘name’:‘lisi’}]}"; Group group = JSON.parseObject(jsonStr, Group.class); System.out.println(group.getId()); System.out.println(group.getName()); System.out.println(group.getUsers().get(0).getId()); System.out.println(group.getUsers().get(0).getName()); } }
net.sf.json.JSONException: Object is null:code
JSONArray或JSONObject轉換時,對象內包含另外一個對象,而該被包含的對象爲NULL,拋出異常htm
參考資料:
一、fastjson Github 地址 :https://github.com/alibaba/fastjson
二、JSON 之 fastjson 解析 : http://blog.sina.com.cn/s/blog_7ffb8dd501013qas.html