我正在使用tmdb来获取电视节目的详细信息。 它具有一个如下所示的端点: https://api.themoviedb.org/3/tv/1399?api_key=API_KEY&append_to_response=season/1,season/2,season/3,season/4,season/5,season/6,season/7,season/8 在此,在响应后附加季节编号以在同一请求中提供该季节的详细信息。这是一个有8个季节的电视节目的例子。 如果说2个季节,则终点为 https://api.themoviedb.org/3/tv/1399?api_key=API_KEY&append_to_response=season/1,season/2
现在,当创建用于处理此请求的模型类时,问题是季节本身作为对象而不是数组返回。所以可能会有很多季节。
{
"id": ...,
...,
...,
"season/1": {...},
"season/2": {...},
"season/3": {...}
}
这些季节中的每个季节都需要一个新的模型类,并且对象的数量也是可变的。我该如何处理?
答案 0 :(得分:0)
The simplest solution for this is just to define your response to be of type ResponseBody
which looks like this:
@GET(value = "/{yourFirstNumber}/tv/{yourSecondNumber}")
Call<ResponseBody> getStuff(@Path("yourFirstNumber") String whateverYouWantToNameThis1,
@Path("yourSecondNumber") String whateverYouWantToNameThis2,
@Query("api_key") String apiKey,
@Query("append_to_response") String appendToResponse);
Just make sure you name these number variables to what they are instead of the phrasing I used as I am unfamiliar with the API.
With this, your request call will look like this:
Call<ResponseBody> call = yourService.getStuff(yourObject);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
L.m("RESPONSE CODE == " + response.code());
if(response.isSuccessful()){
ResponseBody successResponse = response.body();
//This means it was successful (IE a 200)
} else {
ResponseBody errorResponse = response.errorBody();
//This means there was an error (IE a 402)
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//Handle your error here
}
});
From there you can parse your successResponse
in multiple different ways.
For example I use GSON and a few other methods in this class, but it really depends on how you want to parse it. If you want to convert it into a string, use the successResponse.string()
(not a typo, make sure to use string() and not toString() ) method and convert it from the serialized response into one you can easily use.