【问题标题】:How to use @JsonIdentityInfo with circular references?如何将@JsonIdentityInfo 与循环引用一起使用?
【发布时间】:2016-09-15 03:06:09
【问题描述】:

我正在尝试使用来自 Jackson 2 的 @JsonIdentityInfo,如 here 所述。

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

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

当然,天真的方法失败了:

@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 类也不起作用。

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

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

我该怎么做?

【问题讨论】:

  • 这对我来说很好,并生成{"@id":1,"b":{"@id":2,"a":1}}
  • 奇怪。我正在使用 jackson-jr-all-2.7.4.jar 和 com.fasterxml.jackson.jr.ob.JSON。你用过什么 JSON 类?两个类都有注释?
  • 我刚刚创建了一个ObjectMapper 并使用writeValueAsString。 (这是您的 @JsonIdentityInfo 注释。)

标签: java json jackson circular-reference jackson2


【解决方案1】:

似乎jackson-jr 具有杰克逊的一部分功能。 @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 */}

然后

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 引用根对象。

【讨论】:

  • @Sotirios Delimanolis 知道如何忽略 json 响应中的“@id”吗?
  • @SuRa 你说的忽略是什么意思?这就是@JsonIdentityInfo 的意义所在,它提供了一个标识对象的属性(它可以有任何名称)。
  • 从休息客户端检索数据时,我得到 >异常。如何解决这个问题?嵌套的 "a": 1 导致问题。
  • @SuRa 我不确定。 a 应该是常规属性 getAsetA。你必须提供一个完整的例子,考虑提出一个新问题。
  • @SuRa 看起来你想要 JsonIgnore 注释
【解决方案2】:

有几种方法可以解决这种循环引用或无限递归问题。这个link一一详解。我已经解决了我的问题,包括每个相关实体上方的 @JsonIdentityInfo 注释,尽管 @JsonView 是更新的,并且可能是更好的解决方案,具体取决于您的风景。

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

或者使用 IntSequenceGenerator 实现:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class A implements Serializable 
...

【讨论】:

    【解决方案3】:

    在某些情况下,可能需要使用 @JsonProperty("id")

    注释 Id 属性

    例如,就我而言,这使我的应用程序正常运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2011-09-11
      • 2017-10-09
      • 2023-03-27
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多