0

我正在尝试使用 Retrofit 发送请求并能够使用响应。

该服务返回一个像这样的json

  {
     "code" : 0,
     "msg"  : "User received",
     "data" : {
         "name" : "x",
         "tags" : [ "a", "b", "c" ]
     }
   }

结构(代码、消息和数据)相同但数据内部的内容会有所不同。在这个例子中应该映射到一个 User 类。对于其他调用,它将返回帖子列表等。如果出现错误,将没有数据组件,而是一个错误属性。

我虽然可以拥有 Response 类型的特定子类并提示 Retrofit 使用它。

public class Response {
  int code;
  String msg;
}

public class UserResponse extends Response {
  User data;
}

但是当我在返回中没有数据元素时,程序在执行操作时会简单地中断。

4

1 回答 1

0

你可以实现你的 com.retrofit.converter.Convert,如果代码和 msg 属性用于调试;)例如,我使用 Gson 将 json 转换为 java 类型。我将在 fromBody 方法中获取子 JsonElement“数据”作为 gson 参数(public Object fromBody(TypedInput body, Type type) throws ConversionException)。

return gson.fromJson(theDataJsonElement, type);

当然,不要忘记将转换器设置为您的适配器

restAdapter.setConverter(new YourImplementedConverter());
于 2014-03-04T10:16:58.723 回答