首页 > 解决方案 > Jackson @JsonIdentityInfo 和 @JsonIdentityReference 和自定义序列化

问题描述

我正在使用杰克逊在 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”必须继续是 object

这是可能的?

标签: javajsonjpajackson

解决方案


只需将 ref 设置为没有另一个 ref 的对象。

c.ref = new Bean();
c.ref.id = a.id;

推荐阅读