【问题标题】:Multiple objects to be declared in run-time for retrofit model为改造模型在运行时声明多个对象
【发布时间】:2019-04-16 21:51:56
【问题描述】:

我正在使用 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 个季节的电视节目的例子。 如果它有两个季节,那么端点将是 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": {...}
}

每个季节都需要一个新的模型类,并且对象的数量也是可变的。我该如何处理?

Request with 8 seasons

Request with 3 seasons

【问题讨论】:

  • 查看api-themoviedbthemoviedbapi 库中的API 模型。
  • 看着他们俩。他们不处理 append_to_response="seasons" 的情况。

标签: android gson retrofit2


【解决方案1】:

对此最简单的解决方案是将您的响应定义为ResponseBody 类型,如下所示:

@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);

只需确保将这些数字变量命名为它们的名称,而不是我使用的措辞,因为我不熟悉 API。

这样,您的请求调用将如下所示:

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
            }
        });

您可以从那里以多种不同的方式解析您的successResponse

例如我使用GSONthis class 中的其他一些方法,但这实际上取决于您要如何解析它。如果要将其转换为字符串,请使用 successResponse.string()不是错字,请确保使用 string() 而不是 toString() )方法并将其从序列化响应转换为一个您可以轻松使用。

【讨论】:

  • 但问题是我如何制作一个包含可变数量对象的模型,该模型包含季节/1、季节/2、季节/3 等?提出请求的过程很好。但我想知道如何创建一个具有季节变量对象的模型,这些对象在 api 返回时不在数组中。
  • 您能否在您的问题中发布 2 个不同的 API JSON 响应?如果我更好地理解响应主体架构应该是什么样子,我可以重新格式化答案以匹配
猜你喜欢
  • 2016-04-05
  • 2018-04-05
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
相关资源
最近更新 更多