【问题标题】:How to solve "Jackson – Bidirectional Relationships" when object refernce to itself对象引用自身时如何解决“杰克逊-双向关系”
【发布时间】:2018-01-28 13:28:36
【问题描述】:

我正面临“无限递归 (StackOverflowError)”错误 并遵循本手册:http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion 我试图在我的情况下解决它,但在我的情况下似乎不同的原因是对象指向自身。

我的意思是,我有这个对象:

public class PRBOperatorId implements Serializable {
private static final long serialVersionUID = 1L;

public PRBOperatorType type = null;

public PRBOperatorId parentId = null;

public PRBOperatorId childId = null;

public String name = null;
public String[] formats = null;
public String description = null;
public String[] examples = null;
public String returnedFormat = null;
public String comments = null;

服务正在使用它来使用递归方法获取根 Operator 的所有 Operator:

@Override
public PRBOperatorId[] getAllChildren() {
    LinkedList<PRBOperatorId> list = new LinkedList<PRBOperatorId>();
    return getAllChildrenRec(operatorsRoot.getId(), list).toArray(new PRBOperatorId[list.size()]);
}

public Collection<PRBOperatorId> getAllChildrenRec(PRBOperatorId rootId, LinkedList<PRBOperatorId> childrenIds) {
    try {......

我不是通过 java 对象映射数据库表(我实际上并没有对象之间的一对多关系),我只是想在我的逻辑上创建一个 Spring 休息控制器服务。

我该如何解决?

谢谢。

【问题讨论】:

    标签: spring rest jackson


    【解决方案1】:

    你有告诉杰克逊如何识别物体吗?因为如果你这样做了,即使对象指向自身,处理循环引用也没有问题。

    @JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class, 
          property = "name")
    public static class PRBOperatorId implements Serializable
    {
        private static final long serialVersionUID = 1L;
    
        public PRBOperatorId parentId = null;
    
        public PRBOperatorId childId = null;
    
        public String name = null;
    }
    
    public static void main(String[] args) {
        PRBOperatorId op = new PRBOperatorId();
        op.parentId = op;
        op.childId = op;
        op.name = "aaa";
        try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(System.out, op);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    输出:

    {"name":"aaa","parentId":"aaa","childId":"aaa"}
    

    【讨论】:

    • 实际上我已经尝试过这种方法并且它已经为我工作了:),但还是谢谢
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多