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

How to get the array of elements using Retrofit?

我需要通过 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();

最后,RestResponseclass如下:

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
    }
}

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

Expected BEGIN_ARRAY but was BEGIN_OBJECT

错误原因很明确:callback本想获取对象,但获取的是数组。在这种情况下,如果我想获得 <Order> 类型的元素数组,可以做什么?

谢谢!

字段data

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

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

添加Ordersclass:

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

并修改改造调用:

Call<RestResponse<Orders>> getOrdersList();