我有一个使用构建器模式的简单类。
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() 方法实际上返回接口(interface)类型的对象,而不是实现类型。然后我混合注释(因为 Foo 类实际上是第 3 方类)来定义接口(interface) 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 method 'Foo$Builder#build(0 params) has bad return type (FooInterface), not compatible with POJO type (Foo)/p>
看起来像this是罪魁祸首,但我不明白为什么在构建方法中返回父类(super class)型是 Not Acceptable 。有什么想法吗?
最佳答案
它看起来像 Jackson bug。我报告了一个问题: https://github.com/FasterXML/jackson-databind/issues/761
关于java - 使用构建器模式 : "Build method has bad return type, not compatible with POJO type" 的 Jackson 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724859/