使用生成器模式的杰克逊反序列化:"Build method has bad return type, not compatible with POJO type"



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

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实际上是第三方类)来定义接口FooInterface的子类型,如下所示:

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

以及定义Foo类的构建器模式的mixin,如下所示:

@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方法'Foo$Builder#Build(0 params)具有错误的返回类型(FooInterface),与POJO类型(Foo)不兼容

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

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

相关内容

最新更新