日期:2014-05-16  浏览次数:20420 次

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

?

?