2017-08-14 8 views
0

TMDB APIを使用してムービー、テレビ、および人物の検索結果を取得しています。 結果配列では、JSONオブジェクトの型が異なります。 Movieの場合、Object形式はTV Object形式とは異なります。 ので改造で、私たちはJSON配列がレトロフィットで別のエントリが含まれ、これらの状況に対処することができますどのように私の質問があり、この改訂履歴:異なる配列要素を持つJSONを解析する

List<POJOClass> results; 

好きです傾けます。

ここでは、TMDB APIから取得しているJSON形式を示します。 Gson使用

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

:配列のすべての要素が"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 (...) { 
     // ... 
    } 
} 
関連する問題