[英]How to use @JsonIdentityInfo with circular references?
我試圖描述使用@JsonIdentityInfo傑克遜2 這里 。
出於測試目的,我創建了以下兩個類:
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
}
}
}
我怎樣才能做到這一點?
看來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 */}
然后
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
引用根對象的位置。
有幾種方法可以解決此循環引用或無限遞歸問題。 這個鏈接詳細解釋了每一個。 我已經解決了我的問題,包括每個相關實體上面的@JsonIdentityInfo注釋,盡管@JsonView是最新的,根據你的風景,這可能是一個更好的解決方案。
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
或者使用IntSequenceGenerator實現:
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class A implements Serializable
...
在某些情況下,可能需要使用@JsonProperty(“id”)注釋Id屬性
例如,在我的情況下,這使我的應用程序正確運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.