Hey everyone,
I'm trying to solve an inheritance problem where a clear deduction is currently not possible. A toy example:
// BASECLASS
@JsonSubTypes( {
@JsonSubTypes.Type( Child.class )
} )
@JsonTypeInfo( use = JsonTypeInfo.Id.DEDUCTION )
public class BaseModel
{
@JsonProperty( value = "baseOne", required = true )
@JsonPropertyDescription( "some value of base class" )
protected String m_valueOne = "defaultValue";
@JsonProperty( value = "basTwo", required = true )
@JsonPropertyDescription( "another value of base class" )
protected String m_valueTwo;
public BaseModel()
{
}
public BaseModel( final String p_value )
{
m_valueOne = p_value;
}
}
// CHILD CLASS
@JsonInclude( JsonInclude.Include.NON_NULL )
public class Child extends BaseModel
{
@JsonProperty( value = "childValueFirst", required = true )
@JsonPropertyDescription( "some value of child class" )
private String m_child;
public Child()
{
}
public Child( final String p_value )
{
m_child = p_value;
}
}
// TEST
public class TestDemo
{
@Test
public void testDefault() throws JsonProcessingException
{
final List<BaseModel> l_list = Stream.of( new BaseModel(), new Child() ).collect( Collectors.toList() );
final ObjectMapper l_mapper = new ObjectMapper();
final String l_json = l_mapper.writeValueAsString( l_list );
System.out.println( l_json );
final List<BaseModel> l_out = l_mapper.readValue( l_json, new TypeReference<List<BaseModel>>()
{ } );
}
}
Error message (during deserialization):
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class testproject.demo.BaseModel]: Cannot deduce unique subtype of `testproject.demo.BaseModel` (2 candidates match)
The error is quite logical: For the base class, two possibilities can actually be deserialized.
I already have encountered the defaultImpl property:
@JsonTypeInfo( ...,
defaultImpl = BaseClass.class
)
But this leads to a high-priority, default behaviour (all child objects are deserialized with this default class, which is not intended)
. I'd rather like to give it the lowest priority
.
But how actually to solve this? Thanks in advance for any help!