【问题标题】:Retrofit custom converter factory for list type为列表类型改造自定义转换器工厂
【发布时间】:2018-01-29 02:12:44
【问题描述】:

我对一个返回不同 pojos 的 api 有两个不同的调用 -

Call<Verified> verify();

Verified json
-------------
{
  "username":
  "avatar_url":
  "site":
  ...
}

Call<ApiResponse> callapi();

ApiResponse json
----------------
{
  "version":
  "title":
  "url":
  "_meta": {
    "about":
  },
  "items": [
    {
      "id":
      "url":
      "date":
      ...
    },
    ...
  ] 
}

我只想要内部 items 数据,所以我为它编写了一个自定义 Retrofit 信封转换器 -

public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        final Converter<ResponseBody, ApiResponse> delegate =
                retrofit.nextResponseBodyConverter(this, ApiResponse.class, annotations);
        return value -> {
            ApiResponse envelope = delegate.convert(value);
            return envelope.items;
        };
    }

所以现在我可以使用Call&lt;List&lt;Item&gt;&gt; callapi(); 拨打电话。

但由于某种原因,verify() 调用不起作用。在这种情况下,响应始终为空。如果我添加此检查 -

if (type != ApiResponse.class)
    return null;

在转换器中它可以工作,但奇怪的是导致callapi() 无法抛出错误Expected BEGIN_ARRAY but was BEGIN_OBJECT。为什么转换器不工作?另外,如果转换器无法解析 json 响应,Retrofit 不应该退回到下一个转换器吗?

【问题讨论】:

    标签: android retrofit2


    【解决方案1】:

    由于参数中的typeCall 的类型,因此跳过非List&lt;Item&gt; 情况的正确检查是-

    if (!type.equals(Types.newParameterizedType(List.class, Item.class)))
        return null;
    

    如果调用类型不是List&lt;Item&gt;,这允许下一个转换器处理响应。

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-01-17
      • 1970-01-01
      相关资源
      最近更新 更多