net.sf.json.JSONException: There is a cycle in the hierarchy
问题: net.sf.json.JSONException: There is a cycle in the hierarchy! *************************************************************************************************************************************************** 在查问一些资料后,总结出解决该问题的两种办法,现在与大家分享一下。 其一:根据原理来解决,如果需要解析的数据间存在级联关系,而互相嵌套引用,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。 举个例子:现在有实验(Lib)和类别(Libtype)两张表,每个实验都对应着一个类别,那么,在类别的POJO中,就会如下代码: private Integer ltid; //类别ID 当我们写如下代码时,会报错: public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); return null; } 原因很简单,在Libtype中,有一个与List无关的属性值,即libs,我们只需要ltid和ltype,所以报错。 根据我在网上查找的资料,解决办法有如下3种: 1.设置JSON-LIB让其过滤掉引起循环的字段: public ActionForward execute(ActionMapping mapping,HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); } 2.设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环,省事但是数据过于复杂的话会引起数据溢出或者效率低下。 public ActionForward execute(ActionMapping mapping,HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); } 3.最为原始的办法,自己写个JavaBean,用forEach循环,添加到List中,这个方法我看网上有人成功,我没试,但大概过程可以写出来,其结果正确性有待检验。 JavaBean: public LibtypeForm{ int ltid; string ltname; } public ActionForward execute(ActionMapping mapping,HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); List<LibtypeForm> formList = new ArrayList(); LibtypeForm form = new LibtypeForm(); form.setLtid(libtype .getLtid); form.setLtname(libtype.getLtname); formList.add(form); } } 如果有更好的方法,还请高人指点。 转自:http://www.2cto.com/kf/201303/198961.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |