改造:使用不同的数组元素解析JSON

时间:2017-08-14 16:15:47

标签: android json retrofit retrofit2 getjson

我正在使用TMDB API来获取电影,电视和人物的搜索结果。 在结果数组中,JSON对象的类型不同。对于电影,对象格式与电视对象格式不同。 所以在改造中,我不能这样做

List<POJOClass> results;

所以我的问题是我们如何处理这些情况,其中JSON数组在Retrofit中包含不同的条目。

这是我从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"
    ]
}



]

1 个答案:

答案 0 :(得分: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 (...) {
        // ...
    }
}