2017-08-14 38 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 (...) { 
     // ... 
    } 
}