Retrofit2使用@QueryMap映射对象

时间:2018-08-01 02:24:30

标签: android retrofit2

我正在打两个不同的服务电话。一个是/genre/movie/list,JSON如下:

{
  "genres": [
    {
      "id": 28,
      "name": "Action"
    },
    {
      "id": 12,
      "name": "Adventure"
    }
]
}

这给我genreId和相应的名称。我有另一个端点discover/movie,它具有以下JSON。

"results": [
    {
      "vote_count": 263,
      "id": 353081,
      "video": false,
      "vote_average": 7.5,
      "title": "Mission: Impossible - Fallout",
      "popularity": 465.786,
      "poster_path": "/AkJQpZp9WoNdj7pLYSj1L0RcMMN.jpg",
      "original_language": "en",
      "original_title": "Mission: Impossible - Fallout",
      "genre_ids": [
        12,
        28,
        53
      ],
      "backdrop_path": "/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg",
      "adult": false,
      "overview": "When an IMF mission ends badly, the world is faced with dire consequences. As Ethan Hunt takes it upon himself to fulfil his original briefing, the CIA begin to question his loyalty and his motives. The IMF team find themselves in a race against time, hunted by assassins while trying to prevent a global catastrophe.",
      "release_date": "2018-07-25"
    },

以下是服务电话。

@GET("genre/movie/list")
    Observable<HashMap<Integer, Genres>> getMovieGenres(@Query("api_key") String apiKey);
@GET("discover/movie")
    Observable<MovieResponse> discoverMovies(@Query("api_key") String apiKey);

在discover_movie调用中,我有一个genere_ids数组,该数组为我提供了特定类型的id,但没有给我名称。相反,我正在使用端点genre/movie/list进行另一个服务调用。

我的问题是: 如何使用Retrofit2映射ID以获取相应的流派名称?

谢谢!

请澄清一下,我有两个Pojo:

class Movies {
int id;
List<Integer> genre_ids;
}

class MovieGenre {
int id;
String name;
}

在上述情况下,如何获得与Movie类中genre_ids相对应的类型名称。电影类中的genre_ids列表是否映射到MovieGrene中的id?

1 个答案:

答案 0 :(得分:1)

您需要为getMovieGenres方法添加一个对象,而不是一个Hashmap。

赞:

public class MovieGenres {
    public List<Genres> result;
}

假设类型为:

public class Genres {
     public Integer id;
     public String name;
}

并重新实现该方法:

@GET("genre/movie/list")
    Observable<MovieGenres> getMovieGenres(@Query("api_key") String apiKey);

对于您的最后一个(已编辑的)问题,您可以执行以下操作:

class MoviesGenreRelation {
    Movie movie;
    List<MovieGenre> genres = new ArrayList<>();

    MoviesGenreRelation(Movie movie, List<MovieGenre> genres) {
        this.movie = movie;
        for(MovieGenre genre in genres) {
            for(int id in movie.genre_ids) {
                if (id == genre.id)
                    this.genres.add(genre);
            }
        }
    }
}