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

时间:2016-05-31 20:15:04

标签: 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.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
}

我使用@JsonBackReference@JsonManagedReference注释来处理字段,但不知道如何解决接口中的递归问题。是否有可能或者有必要重写这些片段?

1 个答案:

答案 0 :(得分:1)

查看http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

  

一个简单的例子是:

@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
    }
}