android - Retrofit: Parse JSON with different array elements -


i using tmdb api fetch search results of movies, tvs, , people. , in results array, json objects of different type. movie, object format different tv object format. in retrofit, cant this

list<pojoclass> results; 

so question how can deal these situations, json array contains different entries in retrofit.

here's json format getting 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 events of captain america: civil war, peter parker, of mentor tony stark, tries balance life ordinary high school student in queens, new york city, fighting crime superhero alter ego spider-man new threat, 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! musical children's television series made hibbert ralph entertainment bbc aired in 1991. followed adventures of spider, protagonist, , young boy. stories told through song, performed jeff stevenson children, casey , holly, singing backing vocals. style of music varies rock 'n' roll haunting , melancholic, , produced rick cassman. bbc video entitled \"spider! - i'm scary 'cos i'm hairy!\" contained 13 episodes released after series ended. dvd version released later.",     "origin_country": [         "gb"     ] }    ] 

using gson:

assuming every element in array has "media_type" field, can leverage implement own jsondeserializer.

here's template of deserialize() method should 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 (...) {         // ...     } } 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -