如何在循环引用中使用@JsonIdentityInfo? [英] How to use @JsonIdentityInfo with circular references?

查看:1626
本文介绍了如何在循环引用中使用@JsonIdentityInfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jackson 2中的@JsonIdentityInfo,如此处所述。

I am trying to use the @JsonIdentityInfo from Jackson 2 as described here.

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

For testing purposes I created the following two classes:

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

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

Of course, the naive approach failes:

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

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

Adding @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id") to class A and/or class B does not work either.

我希望我能序列化(以及后来反序列化) a 到这样的事情:(虽然不太确定JSON)

I was hoping that I could serialize (and later deserialize) a to something like this: (not too sure about the JSON though)

{
    "b": {
        "@id": 1,
        "a": {
            "@id": 2,
            "b": 1
        }
    }
}

我该怎么做?

推荐答案

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

It seems jackson-jr has a subset of Jackson's features. @JsonIdentityInfo must not have made the cut.

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

If you can use the full Jackson library, just use a standard ObjectMapper with the @JsonIdentityInfo annotation you suggested in your question and serialize your object. For example

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

然后

A a = new A();
B b = new B(a);
a.setB(b);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(a));

将生成

{
    "@id": 1,
    "b": {
        "@id": 2,
        "a": 1
    }
}

其中嵌套的 a 通过 @id 引用根对象。

where the nested a is referring to the root object by its @id.

这篇关于如何在循环引用中使用@JsonIdentityInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆