【问题标题】:Jackson deserialization with builder pattern: "Build method has bad return type, not compatible with POJO type"Jackson 使用构建器模式反序列化:“构建方法的返回类型错误,与 POJO 类型不兼容”
【发布时间】:2015-04-19 01:36:25
【问题描述】:

我有一个使用构建器模式的简单类。

public class Foo implements FooInterface {
  .....
  public static final class Builder {
     public Builder setValueA(String value) {...}
     public Builder setValueB(String value) {...}
     public FooInterface build() {...}
  }
}

请注意,我的 Builder.build() 方法实际上返回的是接口类型的对象,而不是实现的类型。然后我混合注释(因为类 Foo 实际上是第 3 方类)用于定义接口 FooInterface 的子类型,如下所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Foo.class, name = "foo")})
public abstract class FooInterfaceMixin {}

和 mixin 用于定义类 Foo 的构建器模式,如下所示:

@JsonTypeName("foo")
@JsonDeserialize(builder=Foo.Builder.class)
public abstract class FooMixin {}

最后,为了反序列化,我这样做了:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(FooInterface.class, FooInterfaceMixin.class);
mapper.addMixIn(Foo.class, FooMixin.class);

final String jsonString = "{\"type\":\"foo\", \"valueA\":\"a\", \"valueB\":\"b\"}";
FooInterface foo = mapper.readValue(jsonString, FooInterface.class);

我收到错误 Build method 'Foo$Builder#build(0 params) has bad return type (FooInterface), not compatible with POJO type (Foo)

看起来this 是罪魁祸首,但我不明白为什么在构建方法中返回超类型是不可接受的。有什么想法吗?

【问题讨论】:

    标签: java jackson mixins builder json-deserialization


    【解决方案1】:

    它看起来像一个 Jackson 错误。我报告了一个问题: https://github.com/FasterXML/jackson-databind/issues/761

    【讨论】:

    • 谢谢阿列克谢。这很有帮助。没有足够的声誉来支持您的回复,但谢谢。
    • 感谢您报告,修复错误!发布后将在 2.5.3 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2021-04-15
    • 2019-04-09
    • 1970-01-01
    • 2019-06-18
    • 2012-05-08
    • 1970-01-01
    相关资源
    最近更新 更多