【发布时间】:2021-04-12 19:22:01
【问题描述】:
我正在使用 jackson 以 JSON 格式序列化我的对象。该对象是 JPA 实体,因此具有循环关联。
所以,我有这个简单的 POJO:
private static class Bean {
String id;
String description;
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id", scope = Bean.class)
@JsonIdentityReference(alwaysAsId = false)
Bean ref;
}
我序列化这个实例:
Bean a = new Bean();
a.id = "1";
a.description = "The first";
Bean b = new Bean();
b.id = "2";
b.description = "The second";
Bean c = new Bean();
c.id = "3";
b.description = "The last one";
// setup refs
a.ref = b;
b.ref = c;
c.ref = a; // circular
最后我需要这个 JSON:
{
"id": "1",
"description" : "The first",
"ref": {
"id" : "2",
"description" : "The second",
"ref": {
"id" : "3",
"description" : "The last one"
"ref" : {
"id" : "1"
}
}
}
}
我需要循环引用仅序列化“id”属性(并省略其他属性)并且“ref”必须继续作为对象。
有可能吗?
【问题讨论】: