android - Retrofit2 使用@QueryMap 映射对象
问题描述
我正在拨打两个不同的服务电话。一个是/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?
解决方案
您需要为 getMovieGenres 方法添加一个 Object 而不是 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);
}
}
}
}
推荐阅读
- django - 将 Django 迁移到部署时出现此错误,为什么?
- java - 正则表达式:为什么找不到匹配项
- c# - 如何在 Azure Durable Functions 中终止具有自定义状态的 Durable 业务流程
- google-kubernetes-engine - Anthos GKE on-Prem 支持的 Linux 操作系统版本
- spring-boot - tomcat或任何服务器如何将请求传递给spring boot?
- r - 理解 rowwise() 和 c_across()
- sql - ORACLE中count(*)和count(2)有什么区别
- c++ - 链表中具有正值的重复节点(C++)
- android - EXPO Google 登录和 Android 应用问题
- ruby-on-rails - 如何将变量从控制器传递到 Rails 5.2 中的模型?