JSON

JSON-lib学习(3)循环引用

字号+ 作者:H5之家 来源:H5之家 2017-06-07 09:04 我要评论( )

JSON-lib学习(三)循环引用 如果A对象持有B的引用,B对象持有A的引用,这样就形成了循环引用,如果直接使用json-lib转换,会报错: net.sf.json.JSONException:

当前位置:我的异常网»  » JSON-lib学习(3)循环引用

JSON-lib学习(3)循环引用

  网友分享于:2013-07-17  浏览:13次

JSON-lib学习(三)循环引用

如果A对象持有B的引用,B对象持有A的引用,这样就形成了循环引用,如果直接使用json-lib转换,会报错:

net.sf.json.JSONException: There is a cycle in the hierarchy!

import java.util.HashSet; import java.util.Set; public class Aclass { private String name; private int age; private Set<Bclass> policyGoals = new HashSet<Bclass>(); public Aclass() { } public Aclass(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public Set<Bclass> getPolicyGoals() { return policyGoals; } public void setPolicyGoals(Set<Bclass> policyGoals) { this.policyGoals = policyGoals; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return name + "----" + age; } public class Bclass { private String sex; private int address; private Aclass aclass; public Bclass() { } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAddress() { return address; } public void setAddress(int address) { this.address = address; } public Aclass getAclass() { return aclass; } public void setAclass(Aclass aclass) { this.aclass = aclass; } } public static void main(String[] args) throws Exception { Aclass aObj = new Aclass(); aObj.setName("xiu"); aObj.setAge(20); // cretae b Bclass bObj = new Bclass(); bObj.setSex("girl"); bObj.setAddress(100); bObj.setAclass(aObj); aObj.getPolicyGoals().add(bObj); JsonConfig jsonConfig = new JsonConfig(); // jsonConfig.setExcludes(new String[]{"bclass"}); jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); JSONObject jsonObj = JSONObject.fromObject(aObj,jsonConfig); System.out.println(jsonObj.toString()); }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
网友点评