Reputation: 77
I am using TMDB API to fetch search results of Movies, TVs, and People. And in their results array, the JSON objects are of different type. For Movie, the Object format is different from TV Object format. So in retrofit, I cant do like this
List<POJOClass> results;
So my question is how can we deal with these situations, where JSON Array contains different entries in Retrofit.
Here's the JSON format which I am getting from the TMDB API.
{
"results": [
{
"vote_average": 7.4,
"vote_count": 2301,
"id": 315635,
"video": false,
"media_type": "movie",
"title": "Spider-Man: Homecoming",
"popularity": 86.295351,
"poster_path": "/c24sv2weTHPsmDa7jEMN0m2P3RT.jpg",
"original_language": "en",
"original_title": "Spider-Man: Homecoming",
"genre_ids": [
28,
12,
878
],
"backdrop_path": "/vc8bCGjdVp0UbMNLzHnHSLRbBWQ.jpg",
"adult": false,
"overview": "Following the events of Captain America: Civil War, Peter Parker, with the help of his mentor Tony Stark, tries to balance his life as an ordinary high school student in Queens, New York City, with fighting crime as his superhero alter ego Spider-Man as a new threat, the Vulture, emerges.",
"release_date": "2017-07-05"
},
{
"original_name": "Spider!",
"id": 1156,
"media_type": "tv",
"name": "Spider!",
"vote_count": 1,
"vote_average": 10,
"poster_path": null,
"first_air_date": "1991-09-26",
"popularity": 1.063406,
"genre_ids": [],
"original_language": "en",
"backdrop_path": null,
"overview": "Spider! was a musical children's television series made by Hibbert Ralph Entertainment for the BBC which originally aired in 1991. It followed the adventures of a spider, the protagonist, and a young boy. The stories were told through song, performed by Jeff Stevenson with his children, Casey and Holly, singing backing vocals. The style of music varies from rock 'n' roll to haunting and melancholic, and was produced by Rick Cassman. A BBC Video entitled \"Spider! - I'm Only Scary 'cos I'm Hairy!\" which contained all 13 episodes was released soon after the series ended. A DVD version was also released later.",
"origin_country": [
"GB"
]
}
]
Upvotes: 0
Views: 506
Reputation: 54224
Using Gson:
Assuming every element in the array has the "media_type"
field, you can leverage it to implement your own JsonDeserializer
.
Here's the template of a deserialize()
method that should get you started:
@Override
public MovieTVSuperclass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
if (!jsonObject.has("media_type")) {
// return null, throw exception, etc
}
String typeKey = jsonObject.getAsJsonPrimitive("media_type").getAsString();
if (typeKey.equals("movie")) {
return context.deserialize(jsonObject, Movie.class);
}
else if (...) {
// ...
}
}
Upvotes: 0