首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

hibernate List 转JSON发生错的解决办法

2012-10-20 
hibernate List 转JSON发生错的解决方法很多时候数据表都有外键表的,当用hibernate查询结果集时,其关联的

hibernate List 转JSON发生错的解决方法

很多时候数据表都有外键表的,当用hibernate查询结果集时,其关联的对象集也一起来,所以会造成转换JSON发生错误;

以下是一段查询 城市表 的,其关联的主键表是 省份名表,

?

?

以下是方法里的代码,需要 import net.sf.json.*;

?

List list1=new hi.TCityDAO().findAll();
??List li=new ArrayList();//用于装入用来转成JSON的List
??for (Iterator iterator = list1.iterator(); iterator.hasNext();) {
???TCity object = (TCity) iterator.next();
???object.setTProvince(null); //将省份表的对象设为空,不然会出错,出错的原因也在此
???li.add(object);
??}

?

?? //这个地方要注意,如果是javabean对象时要用?JSONObject json=JSONObject.fromObject(objece);
??JSONArray json=JSONArray.fromObject(li);???

?

? System.out.println(json.toString()); //最后输出的JSON字符串

?

另:附出JSON所需要的包,测试过成功,请放心使用

JsonConfig jsonConfig = new JsonConfig();jsonConfig.setExcludes(new String[] { "hibernateLazyInitializer","handler","tProvince"});JSONArray json=JSONArray.fromObject(list1,jsonConfig);
这样就可以了,不用那么麻烦JsonConfig jsonConfig = new JsonConfig();jsonConfig.setExcludes(new String[] { "hibernateLazyInitializer","handler","tProvince"});JSONArray json=JSONArray.fromObject(list1,jsonConfig);
这样就可以了,不用那么麻烦

正解

热点排行