/** * 使用Json-lib序列化Hibernate实体类 * @author 敖士伟 * @version 1.0 2009-10-3 11:12 */ package json; import org.hibernate.Transaction; import dao.EchoMessage; import dao.EchoMessageDAO; import net.sf.json.JSONArray; import net.sf.json.JSONFunction; import net.sf.json.JSONObject; /** * @author az * */ public class MyJSON { /** * @param args */ public static void main(String[] args) { //JsonToBean(); JsonToHibernateBean(); //hiber(); /* boolean[] boolArray = new boolean[] { true, false, true }; JSONArray jsonArray = JSONArray.fromObject(boolArray); System.out.println(jsonArray); //Hibernate实体类 EchoMessageDAO dao = new EchoMessageDAO(); java.util.List<EchoMessage> r = dao.findAll(); for (EchoMessage o : r) { System.out.println(o.getId()); System.out.println(o.getMsg()); JSONObject jsonObject = JSONObject.fromObject(o); System.out.println(jsonObject); System.out.println("-----------"); } dao.getSession().close(); //序列化对象 JSONObject jsonObject = JSONObject.fromObject(new MyBean()); System.out.println(jsonObject); */ } //Hibernate对象持久化 public static void hiber() { EchoMessageDAO dao = new EchoMessageDAO(); Transaction tran = dao.getSession().beginTransaction(); EchoMessage bean = new EchoMessage(); bean.setMsg("Hello11111111"); dao.save(bean); tran.commit(); java.util.List<EchoMessage> r = dao.findAll(); for (EchoMessage o : r) { System.out.println(o.getId()); System.out.println(o.getMsg()); System.out.println("-----------"); } dao.getSession().close(); } /** * JSON反序列化为实体类 * @author 敖士伟 */ public static void JsonToBean(){ String json = "{/"name/":/"json/"}"; JSONObject jsonObject = JSONObject.fromObject( json ); MyBean bean = (MyBean) JSONObject.toBean( jsonObject, MyBean.class ); System.out.println(bean.getName()); } /** * JSON反序列化为Hibernate实体类 * @author 敖士伟 */ public static void JsonToHibernateBean(){ String json = "{/"id/":15,/"msg/":/"Hello11111111/"}"; JSONObject jsonObject = JSONObject.fromObject( json ); EchoMessage bean = (EchoMessage) JSONObject.toBean( jsonObject, EchoMessage.class ); System.out.println(bean.getMsg()); //反序列化后的实体类进行持久化 //ID已设置为自动增长,所以"{/"id/":15无效 EchoMessageDAO dao = new EchoMessageDAO(); Transaction tran = dao.getSession().beginTransaction(); dao.save(bean); tran.commit(); dao.getSession().close(); System.out.println("Over"); } } package json; /** * 实体类 bean * @author 敖士伟 * */ public class MyBean { private String name = "json"; public String getName() { return name; } public void setName(String name) { this.name = name; } }