如果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()); }