如何使用Retrofit获取元素数组?

时间:2015-11-03 17:34:26

标签: android rest retrofit ormlite json-deserialization

我需要通过Rest API获取订单列表。服务器的JSON如下所示:

{
    "meta":
    {
        "status": "SUCCESS",
        "message": "Data was fetched successfully."
    },
    "data":
    {
        "orders":
        [
            {
                "id": "1",
                "seller": "some value"
            },
            {
                "id": "2",
                "seller": "some value"
            }
        ]
    }
}

我使用ORMLite,模型如下所示:

@DatabaseTable(tableName = Order.TABLE_NAME)
public class Order {

    public static final String TABLE_NAME = "Order";

    @DatabaseField
    private String id;

    @DatabaseField
    private String seler;

    public Order() {
    }

    // getters and setters
}

Retrofit 2用于执行查询:

@GET("/api/orders/get")
Call<RestResponse<List<Order>>> getOrdersList();

最后,RestResponse类如下:

public class RestResponse<T> {
    private Meta meta;
    private T data;

    public RestResponse() {
        meta = new Meta();
    }

    public Meta getMeta() {
        return meta;
    }

    public T getData() {
        return data;
    }

    public static class Meta {
        private Status status;
        private String message;

        // getters and setters
    }
}

执行此查询时,出现以下错误:

  

预计BEGIN_ARRAY但是BEGIN_OBJECT

错误的原因很明显:回调旨在获取对象,但获取数组。如果我想获得一个<Order>类型的元素数组?

,在这种情况下可以做些什么

谢谢!

1 个答案:

答案 0 :(得分:1)

字段data

public class RestResponse<T> {
    private Meta meta;
    private T data;
    ...
}

必须是对象,而不是列表。

添加Orders类:

public class Orders {
    List<Order> orders;
    ...
}

修改改装电话:

Call<RestResponse<Orders>> getOrdersList();