1 回答

TA贡献1877条经验 获得超1个赞
由于您有不同的模型列表键<Model>s:,恕我直言,您最好为每个响应使用不同的模型。您必须private List<T> data;从基本响应模型中删除并将其移至子模型。
我已经修改了您的代码并为您的和创建了一些示例products模型customers。下面给出详细的例子,
BasePaginatedResponse.java
public class BasePaginatedResponse {
private int item_count;
private int items_per_page;
private int offset;
public BasePaginatedResponse(
int item_count, int items_per_page, int offset) {
this.item_count = item_count;
this.items_per_page = items_per_page;
this.offset = offset;
}
}
客户响应.java
public class CustomersResponse extends BasePaginatedResponse {
private final List<Customer> customers;
public CustomersResponse(int item_count, int items_per_page, int offset, List<Customer> customers) {
super(item_count, items_per_page, offset);
this.customers = customers;
}
public List<Customer> getCustomers() {
return customers;
}
public class Customer {
private final String id, name;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
}
ProductsResponse.java
public class ProductsResponse extends BasePaginatedResponse {
private final List<Customer> products;
public ProductsResponse(int item_count, int items_per_page, int offset, List<Customer> products) {
super(item_count, items_per_page, offset);
this.products = products;
}
public List<Customer> getProducts() {
return products;
}
public class Customer {
private final String id, name;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
}
在这里,我创建了 3 个类。1 个基本响应类(父类)和 2 个子类。父类包含两个子类共有的字段。
当你使用Retrofit时,你ApiInterface应该是这样的
interface ApiInterface{
@GET("api/v1/customers")
Call<CustomersResponse> getCustomers();
@GET("api/v1/products")
Call<ProductsResponse> getProducts();
}
如果您需要更多说明,请在评论中问我。
添加回答
举报