如何在循环引用中使用@JsonIdentityInfo?
我试图描述使用@JsonIdentityInfo杰克逊2
这里。
为了进行测试,我创建了以下两个类:
public class A{
private B b;
// constructor(s) and getter/setter omitted
}
public class B
{
private A a;
// see above
}
当然,幼稚的方法会失败:
@Testpublic 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? 的全部内容, 来源链接: utcz.com/qa/429329.html