我有一个API,它对模型集合的所有请求都返回以下模式:
{
item_count: 83,
items_per_page: 25,
offset: 25,
<Model>s: [
{ ... },
{ ... },
{ ... },
...
]
}
例如,如果我向/api/v1/customers
发出请求,则此JSON将包含一个customers
密钥。如果我向/api/v1/products
发送请求,则此JSON将包含一个products
密钥。
我要创建一个通用的PaginatedResponse<T>
类来处理item_count
,items_per_page
和offset
变量,如下所示:
public class PaginatedResponse<T> {
private int item_count;
private int items_per_page;
private int offset;
private List<T> data;
public PaginatedResponse<T>(int item_count, int items_per_page, int offset, List<T> data) {
this.item_count = item_count;
this.items_per_page = items_per_page;
this.offset = offset;
this.data = data;
}
public List<T> getData() {
return this.data;
}
}
是否可以将JSON解析为我的PaginatedResponse POJO?
答案 0 :(得分: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;
}
}
CustomersResponse.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();
}
如果您需要更多说明,请在评论中问我。