Search code examples
javajsonjacksonjson-deserialization

jackson not able to serialize a list of polymorphic objects


I have an abstract class which I need to serialize as a list of items and send it over the network in json format.

@JsonTypeInfo(
    use=JsonTypeInfo.Id.NAME,
    include= As.PROPERTY,
    property="searchMatchType",
    defaultImpl = NoClass.class,
    visible = true)
@JsonSubTypes({
    @Type(value = Match.class, name = "MATCH"),
    @Type(value = SynonymMatchA.class, name = "SYNONYM_MATCH_A"),
    @Type(value = SynonymMatchB.class, name = "SYNONYM_MATCH_B")
})
public abstract class SearchResult {

    private TypeA typeA;

    private SearchMatchType searchMatchType;

    @JsonCreator
    public SearchResult(
           @JsonProperty("searchMatchType") SearchMatchType searchMatchType,
           @JsonProperty("typeA") TypeA typeA) {
        this.searchMatchType = searchMatchType;
        this.typeA = typeA;
    }  
}

I know that we cannot serialize a list of objects in java because java complier applies type erasure at compile time. So I created a wrapper class as below and returning this from the main controller instead of list.

public class SearchResultList {

    private final List<SearchResult> searchResults;

    @JsonCreator
    public SearchResultList(
          @JsonProperty("searchResults") List<SearchResult> searchResults) {
        this.searchResults = searchResults;
    }
}

I am populating the list with objects of type MATCH,SYNONYM_MATCH_A and SYNONYM_MATCH_B which are subtypes of SearchResult class. Now in the json I am able to see base class fields but not able to see derived class fields from classes MATCH,SYNONYM_MATCH_A and SYNONYM_MATCH_B. I am able to see these complete objects when I inspect the list on the server but not in the json which is serialized from list.


Solution

  • I wasn't using getters for the fields in my derived class, so jackson wasnt able to get the value of the the fields while serializing from object to json format. Once I put the getters it was able to serialize properly.