jsonString javabean相互回転

2258 ワード

import java.util.Date;

public class Student {
	private String name;
	private Date birthday;
	private int age;
	private boolean isboy ;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isIsboy() {
		return isboy;
	}
	public void setIsboy(boolean isboy) {
		this.isboy = isboy;
	}


}

 
テストクラス
 
 
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class test {
	public static void main(String[] args){
		//JSONObject json = "{}";
		//json 
		String jsonString = "{name:' ' ,age:'9',isboy:true}";


		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
		System.out.println(stu.getName());

		//bean 2 jsonObject
		JSONObject jsonobject  = JSONObject.fromObject(stu);
		System.out.println(jsonobject .toString());



		// 
		String jsonString1 = "{name:' 1',birthday :'2002-09-01', age:'9',isboy:true}";
		String[] dateFormats1 = new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"};
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats1));

		JSONObject jsonObject1 = JSONObject.fromObject(jsonString1);
		Student stu1 = (Student) JSONObject.toBean(jsonObject1, Student.class);
		System.out.println(stu1.getName());

		//bean 2 jsonObject
		JSONObject jsonobject1 = JSONObject.fromObject(stu1);
		System.out.println(jsonobject1.toString());
	}
}

 
 
日付属性が空の場合、removeの属性をまとめます.