import java.util.List;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;
/**
* 使用阿里巴巴FastJson将对象转换成json字符串、将json字符串装换成对象
*
* @author higher2016
* @2016-12-27
*/
public class FastJsonDemo {
public static void main(String[] args) {
// 构建用户geust
User guestUser = new User();
guestUser.setName("guest");
guestUser.setAge(28);
// 构建用户root
User rootUser = new User();
rootUser.setName("root");
guestUser.setAge(35);
// 构建用户组对象
UserGroup group = new UserGroup();
group.setName("admin");
group.getUsers().add(guestUser);
group.getUsers().add(rootUser);
//将对象转换为json字符串
String jsonString = JSON.toJSONString(group);
System.out.println("jsonString:"+jsonString);
//将json字符串转换成对象
UserGroup group1 = JSON.parseObject(jsonString, UserGroup.class);
System.out.println(group1);
//数组装换为json字符串
User[] users = new User[2];
users[0] = guestUser;
users[1] = rootUser;
String jsonString1 = JSON.toJSONString(users);
System.out.println("jsonString1:"+jsonString1);
//json字符串转换为List
List<User> user2 = JSON.parseArray(jsonString1, User.class);
System.out.println(user2);
}
class User {
private String name;
private int age;
public User() {
super();
// TODO Auto-generated constructor stub
}
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:"+this.name+", age:"+this.age+" }";
}
}
class UserGroup {
private String name;
private List<User> users = new ArrayList<User>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUser(List<User> users) {
this.users = users;
}
public UserGroup() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString(){
return "UserGroup:{ name="+this.name+", user="+this.users+" }";
}
}
}
网友评论