我正在访问一个 REST API,它返回 JSON 格式的资源列表:
{
"products": [
{ ... },
{ ... }
]
}
当列表很大(> 50 项)时,响应将被分页,并pagination
在返回的 JSON 的根节点中添加一个附加项,如下所示:
{
"pagination": {
"results" : 490,
"page" : 1,
"page_size" : 50,
"pages" : 10
},
"products": [
{ ... },
{ ... }
]
}
为了满足这一点,我有一个PaginatedList
看起来像这样的类(可能不是最好的名字):
public class PaginatedList
{
[JsonProperty("pagination")]
public Pagination Pagination { get; set; }
}
一个ProductList
看起来像这样的类:
public class ProductList : PaginatedList
{
[JsonProperty("products")]
public List<Product> Products { get; set; }
}
像这样的Pagination
课程:
public class Pagination
{
[JsonProperty("results")]
public int Results { get; set; }
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("page_size")]
public int PageSize { get; set; }
[JsonProperty("pages")]
public int Pages { get; set; }
}
要检索我的资源,我使用:
public List<Product> GetProducts()
{
return getResourceAsync<ProductList>(productsResourceName).Result.Products;
}
和:
async Task<T> getResourceListAsync<T>(string resourceName)
{
var url = string.Concat(BaseUrl, resourceName);
var credentials = new NetworkCredential(Username, Password);
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler)) {
var response = await client.GetAsync(url);
var contentString = await response.Content.ReadAsStringAsync();
var resource = await JsonConvert.DeserializeObjectAsync<T>(contentString);
return resource;
}
}
在方法中添加对分页的支持GetProducts
非常容易,但这意味着为每种类型的资源(产品、客户、供应商等)复制非常相似的代码。问题是,我如何获得该getResourceListAsync
方法以使其支持分页和非分页列表并适用于不同的资源?