如何将@JsonIdentityInfo 与循环引用一起使用? [英] How to use @JsonIdentityInfo with circular references?

查看:28
本文介绍了如何将@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天全站免登陆