如何在循环引用中使用@JsonIdentityInfo?

Bur*_*ard 8 java json circular-reference jackson jackson2

我试图描述使用@JsonIdentityInfo杰克逊2 这里.

出于测试目的,我创建了以下两个类:

public class A
{
    private B b;
    // constructor(s) and getter/setter omitted
}
public class B
{
    private A a;
    // see above
}
Run Code Online (Sandbox Code Playgroud)

当然,天真的方法很糟糕:

@Test
public void testJacksonJr() throws Exception
{
    A a = new A();
    B b = new B(a);
    a.setB(b);
    String s = JSON.std.asString(a);// throws StackOverflowError
    Assert.assertEquals("{\"@id\":1,\"b\":{\"@id\":2,\"a\":1}}", s);
}
Run Code Online (Sandbox Code Playgroud)

添加@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")到A类和/或B类也不起作用.

我希望我可以序列化(后来反序列化)a到这样的东西:(虽然不太确定JSON)

{
    "b": {
        "@id": 1,
        "a": {
            "@id": 2,
            "b": 1
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Sot*_*lis 19

看来jackson-jr有Jackson的一部分功能.@JsonIdentityInfo一定不能削减.

如果您可以使用完整的Jackson库,只需使用ObjectMapper带有@JsonIdentityInfo您在问题中建议的注释的标准并序列化您的对象.例如

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class A {/* all that good stuff */}

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class B {/* all that good stuff */}
Run Code Online (Sandbox Code Playgroud)

然后

A a = new A();
B b = new B(a);
a.setB(b);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(a));
Run Code Online (Sandbox Code Playgroud)

会产生

{
    "@id": 1,
    "b": {
        "@id": 2,
        "a": 1
    }
}
Run Code Online (Sandbox Code Playgroud)

嵌套a是指它的根对象@id.