Add `MapperFeature.USE_BASE_TYPE_AS_DEFAULT_IMPL` to use declared base type as `defaultImpl` for polymorphic deserialization
See original GitHub issueI use @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type")
for interfaces and abstract classes and it works as expected.
Now I have a case where the JSON string does not contain the ‘type’ property (external interface) but I know the concrete class to which this JSON string should be mapped.
When I now use objectMapper.readValue(jsonString, ConcreteClass.class)
then I get an exception that the ‘type’ property is missing. That’s bad because I tell Jackson that the ‘type’ is ‘ConcreteClass.class’ so I want that Jackson tolerates the missing ‘type’ property. In other words: Please use the given class as ‘defaultImpl’ (see JsonTypeInfo attribute defaultImpl) if no JsonTypeInfo defaultImpl attribute was set but a concrete class was given.
Or is there another way to define a ‘defaultImpl’ when using readValue()?
Thank you!
Example:
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type")
public interface MyInterface {
String getName();
void setName(String name);
}
public class MyClass implements MyInterface {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This works:
{
"name": "name",
"type": ".MyClass"
}
objectMapper.readValue(jsonString, MyInterface.class);
This not (but it would be very nice if you can make it work):
{
"name": "name"
}
objectMapper.readValue(jsonString, MyClass.class);
Issue Analytics
- State:
- Created 8 years ago
- Reactions:13
- Comments:25 (14 by maintainers)
Top GitHub Comments
You can specify “default type” with
@JsonTypeInfo(defaultImpl=DefaultImplementClass.class)
As to whether it’d be possible to force use of actual sub-class… I don’t know off-hand. It is an interesting idea, and if that is possible to implement could make sense. But I’d have to see how code path works for this particular case; polymorphic type handling is quite specialized system.
Thank you for the hint regarding
@JsonTypeInfo(defaultImpl=...)
. Here, it works perfectly when being used in subclasses and also solves my stackoverflow question: How to deserialize JSON having refrences to abstract types in Jackson.