相关疑难解决方法(0)

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

我试图描述使用@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)

我怎样才能做到这一点?

java json circular-reference jackson jackson2

8
推荐指数
1
解决办法
3万
查看次数

标签 统计

circular-reference ×1

jackson ×1

jackson2 ×1

java ×1

json ×1