Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

How to use Jackson to deserialize using sub types with a nullable property?

$
0
0

Context: I have two different JSON responses returned from an API. The first is the combined (movie & tv) crew credit information, and the second is only the tv crew credit information.

The first JSON specifies the property media_type which determines which class it should deserialize to. Below you can see it can either be movie or tv. For my outer model class CombinedCredits, this works.

The issue arises when I try to deserialize the second JSON, for the outer model class TvCredits. The JSON provided does not include a media_type property because it is expected to be for tv only.

I get the following error when trying to deserialize for TvCredits:

com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class info.movito.themoviedbapi.model.people.TvCrew]: missing type id property 'media_type' (for POJO property 'crew') at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 25, column: 9] (through reference chain: info.movito.themoviedbapi.model.people.TvCredits["crew"]->java.util.ArrayList[0])

I assume this is an issue with using the interface when the JSON does not have the expected deserialization property, but how else can I solve this without duplicating lots of code?

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "media_type")@JsonSubTypes({    @JsonSubTypes.Type(value = MovieCrew.class, name = "movie"),    @JsonSubTypes.Type(value = TvCrew.class, name = "tv")})public interface Crew {    ...}
public class TvCrew implements Crew {    ...}
public class MovieCrew implements Crew {    ...}
public class CombinedCredits {    private List<Crew> crew;    ...}
public class TvCredits {    private List<TvCrew> crew;    ...}

Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>