1
votes

Having a class DocumentMapping that contains various fields. One of those fields is a class BinaryDocumentMapping which is abstract. BinaryDocumentMapping is extended by 3 other classes ExcelDocumentMapping, XMLDocumentMapping and CSVDocumentMapping.

So I'm having :

public class DocumentMapping{

    @JsonSubTypes({ @JsonSubTypes.Type(value = ExcelDocumentMapping.class, name = "EXCEL"),
            @JsonSubTypes.Type(value = CsvDocumentMapping.class, name = "CSV"), @JsonSubTypes.Type(value = XmlDocumentMapping.class, name = "XML") })
    private BinaryDocumentMapping binary = null;

where

public abstract class BinaryDocumentMapping
    implements Serializable {

and

@JsonTypeName("CSV")
public class CsvDocumentMapping

The serialization works ok but I have problem when reading the json into an object:

mapper.reader().withType(DocumentMapping.class).readValue(jsonData);

which throws

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.documentmapping.BinaryDocumentMapping, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

Is there any way to deserialize into the concrete class based on the type ?

1
you need to specify @JsonTypeInfo (stackoverflow.com/a/11798485/1976843) - JEY
Correct, @JEY. Thanks ! Please post as answer so I can close. - Sergiu
I posted my comment as an answer. - JEY

1 Answers