JSON在处置hibernate中的cascade对象时的解决方案

JSON在处理hibernate中的cascade对象时的解决方案

如果数据间存在级联关系,在hibernate中极容易嵌套而抛出net.sf.json.JSONException: There is a cycle in the hierarchy异常。

解决办法是给json指定过滤器。如:

JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter(){
public boolean apply(Object source, String name, Object value){
  if (name.equals("goodsType") || name.equals("goodsGroup")){
     return true;
  }
  return false;
}
});
JSONArray jsonForGoodsTypes = JSONArray.fromObject(goodsTypes,config);

这将过滤掉goodsType和goodsGroup两个属性,避免了嵌套。

现在更好的解决办法(推荐):

JsonConfig config = new JsonConfig();
config.setExcludes( new String[]{ "execludeField" , "fromPage" } ) ;

把不需要的字段放到这个数组中就可以了!

JSONObject jobj1=JSONObject.fromObject(orderLevel,jsconfig);