Jackson deserialization with builder pattern: "Build method has wrong return type, incompatible with POJO type"
I have a simple class that uses the builder pattern.
public class Foo implements FooInterface {
.....
public static final class Builder {
public Builder setValueA(String value) {...}
public Builder setValueB(String value) {...}
public FooInterface build() {...}
}
}
Note that my Builder.build () method actually returns an interface type object, not an implemented type. Then I mix annotations (because the Foo class is actually a third-party class) to subtype the FooInterface like so:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Foo.class, name = "foo")})
public abstract class FooInterfaceMixin {}
And a mixin to define a Foo class builder template, for example:
@JsonTypeName("foo")
@JsonDeserialize(builder=Foo.Builder.class)
public abstract class FooMixin {}
Finally, to deserialize, I do:
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);
I am getting the error Build method 'Foo $ Builder # build (0 params) has wrong return type (FooInterface), not POJO compatible type (Foo)
It looks like this one is the culprit, but I don't understand why returning a supertype in an assembly method would not be acceptable. Any ideas?
source to share
Sounds like Jackson's mistake. I reported the issue: https://github.com/FasterXML/jackson-databind/issues/761
source to share