自身一对多关联模型的JSON转换

       最近又遇到了一个问题, 这里有一个一对多自身关联的模型
 1 Class Tree
 2 {
 3   private String id;
 4   private String name;
 5   private Set<tree> children = new HashSet<Tree>();
 6   public void setId(String id)
 7   {
 8         this.id = id;
 9   }

10   public String getId()
11   {
12         return this.id;
13   }

14    
15}
然后我用JSON把这个模型转换成string的时候会报错:will throw a JSONException if a cycle is found.后来去查了下JSON的API发现是我的JSON转换策略有问题。原文是这样的:
public abstract class CycleDetectionStrategy
extends Object
 

Base class for cycle detection in a hierarchy.
The JSON spec forbides cycles in a hierarchy and most parsers will raise and error when a cycle is detected. This class defines a contract for handling those cycles and two base implementations:

  • STRICT - will throw a JSONException if a cycle is found.
  • LENIENT - will return an empty array or null object if a cycle is found.

说的很清楚了所以必须做点修改像这样:
 1 public   class  TreeAction  extends  BaseActionSupport {
 2    private static final CycleDetectionStrategy CycleDetectionStrategy = null;
 3    public String getAllTree()
 4    {
 5        JsonConfig jsonConfig=new JsonConfig();
 6        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
 7        tree = regionService.getTreeChildren("402881821a7fbf10011a7fc2d3ae0001");
 8        JSONObject array = JSONObject.fromObject(tree,jsonConfig);
 9        System.out.println("$$$$$$$$$$"+array.toString()+"$$$$$$$$$$$$$$");
10        return SUCCESS;
11    }

12}

这样修改以后转换就正常啦~~~。呵呵,HIBERNATE还有好多问题我没解决烦恼中。。。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值