【问题标题】:Jackson @JsonIdentityInfo and @JsonIdentityReference and custom serializationJackson @JsonIdentityInfo 和 @JsonIdentityReference 和自定义序列化
【发布时间】: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”必须继续作为对象

有可能吗?

【问题讨论】:

    标签: java json jpa jackson


    【解决方案1】:

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

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

    【讨论】:

    • 序列化必须保证这一点,而不是开发者。这只是一个例子,我的真实场景有一个更复杂的(比如带有关联的 JPA 实体)序列化。
    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2015-07-11
    • 2016-01-11
    • 2018-04-05
    相关资源
    最近更新 更多