日期:2014-05-16  浏览次数:20361 次

fastjson的使用

// 实体类Group定义

public class Group {
	
	private int id;
	private List<Student> array;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public List<Student> getArray() {
		return array;
	}
	public void setArray(List<Student> array) {
		this.array = array;
	}
}

?

// 实体类Student定义

public class Student {
	
	private String name;
	private int age;
	private String address;
	private String email;
	
	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;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	@Override
	public String toString(){
		StringBuffer buffer = new StringBuffer();
		buffer.append("name:").append(name).append(",\t");
		buffer.append("age:").append(age).append(",\t");
		buffer.append("address:").append(address).append(",\t");
		buffer.append("email:").append(email);
		
		return buffer.toString();
		
	}
}

?// 测试类

public class Test {
	
	/*
	public static void main(String[] args) throws Exception{
		
		Student student = new Student();
		student.setName("hejinyun");
		student.setAge(27);
		student.setAddress("beijing");
		student.setEmail("hejinyun@gmail.com");
		
		String jsonString = JSON.toJSONString(student);
		System.out.println("student->"+student);
		System.out.println("jsonString->"+jsonString);
		Student jsonStudent = JSON.parseObject(jsonString, Student.class);
		System.out.println("jsonStudent->"+jsonStudent);
		
		
	}
	*/
	
	public static void main(String[] args) throws Exception{
		Group group = new Group();
		
		Student stud1 = new Student();
		stud1.setName("Jack");
		stud1.setAge(18);
		stud1.setAddress("beijing");
		stud1.setEmail("jack@163.com");
		
		Student stud2 = new Student();
		stud2.setName("Lily");
		stud2.setAge(19);
		stud2.setAddress("shanghai");
		stud2.setEmail("lily@sina.com");
		
		List<Student> array = new ArrayList<Student>();
		array.add(stud1);
		array.add(stud2);
		group.setId(1);
		group.setArray(array);
		
		String jsonString = JSON.toJSONString(group);
		System.out.println("jsonGroup->"+jsonString);
		Group jsonGroup = JSON.parseObject(jsonString, Group.class);
		System.out.println("jsonGroup->"+jsonGroup);
	}
}

?

//? 测试结果

{
    "array": [
        {
            "address": "beijing",
            "age": 18,
            "email": "jack@163.com",
            "name": "Jack"
        },
        {
            "address": "shanghai",
            "age": 19,
            "email": "lily@sina.com",
            "name": "Lily"
        }
    ],
    "id": 1
}

?