1.導入:java
compile 'com.alibaba:fastjson:1.2.41'
2.使用:json
public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
public class UserGroup { private String name; private List<User> users = new ArrayList<>(); 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; } @Override public String toString() { return "UserGroup [name=" + name + ", users=" + users + "]"; } }
代碼實例:數組
User guestUser = new User(); guestUser.setName(null); guestUser.setAge(28); // 構建用戶root User rootUser = new User(); rootUser.setName("root"); guestUser.setAge(35); // 構建用戶組對象 UserGroup group = new UserGroup(); group.setName(null); group.getUsers().add(guestUser); group.getUsers().add(rootUser); // 用戶組對象轉JSON串 String jsonString = JSON.toJSONString(group); Log.e("Demo12Activity","jsonString:" + jsonString); // JSON串轉用戶組對象 UserGroup group2 = JSON.parseObject(jsonString, UserGroup.class); Log.e("Demo12Activity","group:"+group2); // 構建用戶對象數組 User[] users = new User[2]; users[0] = guestUser; users[1] = rootUser; // 用戶對象數組轉JSON串 String jsonString2 = JSON.toJSONString(users); System.out.println("jsonString2:" + jsonString2); // JSON串轉用戶對象列表 List<User> users2 = JSON.parseArray(jsonString2, User.class); Log.e("Demo12Activity","users2:" + users2); User user1 = users2.get(0); Log.e("Demo12Activity","user1:" + user1.getName());
運行結果:ide
jsonString:{"users":[{"age":35},{"age":0,"name":"root"}]}
group:UserGroup [name=null, users=[User [name=null, age=35], User [name=root, age=0]]]
users2:[User [name=null, age=35], User [name=root, age=0]]
user1:null