Java 如何解析JSON序列化中的循环引用?

Java 如何解析JSON序列化中的循环引用?,java,json,spring-boot,jackson,Java,Json,Spring Boot,Jackson,请帮助我以JSON格式存储树结构。我得到 ERROR 6444 --- [nio-8090-exec-1] o.a.c.c.C.[.[.[/]. [dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.S

请帮助我以JSON格式存储树结构。我得到

ERROR 6444 --- [nio-8090-exec-1] o.a.c.c.C.[.[.[/].    [dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.StackOverflowError] with root cause

java.lang.StackOverflowError: null
    at java.lang.Class.getGenericInterfaces(Class.java:912) ~[na:1.8.0_40]
    at com.fasterxml.jackson.databind.type.TypeFactory._doFindSuperInterfaceChain(TypeFactory.java:1260) ~[jackson-databind-2.6.6.jar:2.6.6]
    at com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(TypeFactory.java:1254) ~[jackson-databind-2.6.6.jar:2.6.6]
    // more stacktrace here...
关于以下代码:

public class CustomASTNode implements ASTNode {
    private final CustomNode node; // simple property
    private final ASTNodeID id; // simple property
    @JsonBackReference
    private final ASTNode parent; // circular property!
    @JsonManagedReference
    private List<ASTNode> children = new ArrayList<>(); // circular property!
    // more code
}

public interface ASTNode extends Iterable<ASTNode> { // ?
    // more code
}
public类CustomASTNode实现ASTNode{
私有最终CustomNode节点;//简单属性
私有最终ASTNodeID;//简单属性
@JsonBackReference
私有最终节点父节点;//循环属性!
@JsonManagedReference
private List children=new ArrayList();//循环属性!
//更多代码
}
公共接口ASTNode扩展了Iterable{//?
//更多代码
}
我使用
@JsonBackReference
@JsonManagedReference
注释来处理字段,但不知道如何解决接口中的递归。是否有可能或可能有必要重写这些代码段?

请看

一个简单的例子是:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Identifiable
{
    public int value;

    public Identifiable next;
}
如果我们创建了一个由两个值组成的循环,比如:

Identifiable ob1 = new Identifiable();
ob1.value = 13;
Identifiable ob2 = new Identifiable();
ob2.value = 42;
// link as a cycle:
ob1.next = ob2;
ob2.next = ob1;
并使用以下命令进行序列化:

String json = objectMapper.writeValueAsString(ob1);
我们将获得以下JSON序列化:

{
    "@id" : 1,
    "value" : 13,
    "next" : {
        "@id" : 2,
        "value" : 42,
        "next" : 1
    }
}

如果有循环引用,它就不是树。@AndyTurner是的,但我说的是接口定义中的循环引用(
ASTNode扩展Iterable
),而树是使用
父项
子项
字段从
自定义节点
对象构建的,这一点必须清楚,你是说你的ASTNode是一个带循环的图形吗?谢谢,
@JsonIdentityInfo
注释从接口定义中删除
扩展了Iterable
,解决了问题。