【问题标题】:Support a varying object data type with Retrofit使用 Retrofit 支持不同的对象数据类型
【发布时间】:2014-10-18 00:45:42
【问题描述】:

下面是我需要Android应用以JSON形式传递给REST API的数据的数据结构的描述。特别值得注意的是“响应”字段,它的类型各不相同。有时它是一个布尔值,有时是一个整数,或者它可以是一个字符串或一个整数数组。由于各种原因,服务器 API 不能轻易更改,所以我必须按原样支持它。

如何自定义我的 Retrofit 用途以适应这样的数据类型变化的字段?我之前为 Retrofit 的 rest 适配器编写了类型适配器,它非常适合处理响应,但是请求类型适配器的等价物是什么?

array(
        array(
                question_id => 1,
                route_id => 1,
                response => true,
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 2,
                route_id => 1,
                response => ’this is a string',
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 3,
                route_id => 1,
                response => 1,
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 4,
                route_id => 1,
                response => array(
                        1234,
                        178,
                        109
                ),
                timestamp => ‘2014-01-01 20:01:01'
        ),
)

【问题讨论】:

标签: android retrofit


【解决方案1】:

事实证明,这非常容易。如果 Retrofit 在模型类中传递 Object 类型的对象,它会智能地将它们转换为正确的 JSON 字段类型。

public class MyModel {

    // Renders to JSON as boolean, int, String etc depending on the underlying class
    public Object response; 

}

【讨论】:

    【解决方案2】:

    您可以提供自己的 json 转换器来在内部处理它。 How to handle Dynamic JSON in Retrofit?

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2020-07-07
      • 2018-02-10
      • 1970-01-01
      • 2019-09-15
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多