【问题标题】:How to parse the json when having same response but different mapping具有相同响应但映射不同时如何解析json
【发布时间】:2014-04-02 05:58:39
【问题描述】:

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

服务返回一个这样的json

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

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

虽然我可以有一个响应类型的特定子类并提示 Retrofit 使用它。

public class Response {
  int code;
  String msg;
}

public class UserResponse extends Response {
  User data;
}

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

【问题讨论】:

  • 您正在尝试做的事情并没有什么特别的错误。你能发布一个你得到的例外的日志吗?你用什么来解析 de JSON 响应? ¿格森? ¿杰克逊?
  • 我从头开始编写代码并且它工作正常。可证明使用方式有问题。

标签: retrofit


【解决方案1】:

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

return gson.fromJson(theDataJsonElement, type);

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

restAdapter.setConverter(new YourImplementedConverter());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多