【问题标题】:Jackson deserialize JsonIdentityReference (alwaysAsId = true)Jackson 反序列化 JsonIdentityReference (alwaysAsId = true)
【发布时间】:2013-08-19 03:34:10
【问题描述】:

跟进这个问题:Question here

@JsonIdentityReference(alwaysAsId = true)@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class) 在序列化结束时效果很好,但在反序列化时效果不佳,因为它无法解析对象 ID 引用。

有没有办法让它反序列化?编写自定义反序列化器似乎有点过头了。

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    您可以使用简单的 setter 反序列化器来代替自定义反序列化器:

    public class Container {
        @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
        @JsonIdentityReference(alwaysAsId = true)
        private Foo foo;
    
        public Foo getFoo() {
            return foo;
        }
        public Container setFoo(Foo foo) {
            this.foo = foo;
            return this;
        }
        @JsonProperty("foo")
        public void setFoo(String id) {
            foo = new Foo().setId(id);
        }
    }
    

    {"foo":"id1"} 的示例字符串在Jackson 2.5.2 中使用此方法正确序列化

    【讨论】:

    • 如果 Foo 有更多的属性而不仅仅是 id 则这不起作用,因此必须链接现有实例。
    • setId 不应该返回 Foo 的实例,你应该让它成为一个 builder insted
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2021-01-19
    • 1970-01-01
    • 2013-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多