2017-08-14 54 views
0

我使用TMDB的API來獲取電影,電視和人民的搜索結果不同的數組元素解析JSON。 而在它們的結果陣列中,JSON對象是不同的類型。對於電影,對象格式與電視對象格式不同。 所以在改造,我不能做這樣的改造:與

List<POJOClass> results; 

所以我的問題是我們如何能夠應對這些情況,其中JSON數組包含改造不同的條目。

下面是我從我的TMDB API獲取JSON格式。

{ 
"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" 
    ] 
} 



] 

回答

0

使用GSON:

假設數組中的每個元素有"media_type"場,你可以利用它來實現自己的JsonDeserializer

這裏有一個deserialize()方法,應該讓你開始模板:

@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 (...) { 
     // ... 
    } 
}