Json - 使用json-lib完成javabean对象转换成json字符串

例子代码:

Student.java

 
public class Student {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
 
    public String toString() {
        return "姓名:" + this.name + " ID: " + this.id + " 地址: " + this.address + " 生日: " + this.birthday + " 邮箱: " + this.email;
    }

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Birthday getBirthday() {
		return birthday;
	}

	public void setBirthday(Birthday birthday) {
		this.birthday = birthday;
	}
    
}


Birthday.java

public class Birthday {

	public Birthday() {}
    
    public Birthday(String birthday) {
        super();
        this.birthday = birthday;
    }
    
    private String birthday;
    
    
    @Override
    public String toString() {
        return this.birthday;
    }

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

}

Test.java

public class JsonlibTest {
	private static JSONArray jsonArray = null;
	private static JSONObject jsonObject = null;

	private static Student stu = null;
	private Train train = null;

	public static void main(String args[]){
		jsonArray = new JSONArray();
		jsonObject = new JSONObject();

		stu = new Student();

		stu.setAddress("山东青岛");
		stu.setEmail("[email protected]");
		stu.setId(1);
		stu.setName("kalision");

		Birthday day = new Birthday();
		day.setBirthday("1989-01-25");

		stu.setBirthday(day);
		
		System.out.println(JSONObject.fromObject(stu).toString());
	}}

输出:

{"address":"山东青岛","birthday":{"birthday":"1989-01-25"},"email":"[email protected]","id":1,"name":"kalision"}

当然也可以用JSONArray.fromObject(stu).toString(),JSONSerializer.toJSON(stu).toString()

 它们两个的区别大家可以参考另外一篇文章:


http://blog.csdn.net/kalision/article/details/7695162



你可能感兴趣的:(Json - 使用json-lib完成javabean对象转换成json字符串)