简体   繁体   English

循环调用C# await调用从web中取出JSON数据

[英]Calling C# await calls in a loop to retrieve JSON data from web

I have a method that calls an API with HttpClient and build a list of Customers as IEnumerable<Customer> .我有一个使用HttpClient调用 API 并将客户列表构建为IEnumerable<Customer>的方法。 The way this API works is that it will return only 100 customers at a time, and will provide another link in the JSON content to fetch again the next 100. API 的工作方式是一次只返回 100 个客户,并在 JSON 内容中提供另一个链接以再次获取下 100 个客户。

How can I structure this code to iteratively fetch the records until all are fetched and build a large IEnumerable<Customer> and return from this method.我如何构建此代码以迭代获取记录,直到获取所有记录并构建一个大型IEnumerable<Customer>并从此方法返回。 It is okay to break this large method to another small one.把这个大方法拆成另一个小方法也行。 I don't want a synchronous process.我不想要同步过程。

Task<IEnumerable<Customer>> GetCustomers(string url)
{
  HttpClient client = new HttpClient();
  HttpResponseMessage response = await client.GetAsync(url);
  response.EnsureSuccessStatusCode();
  string responseBody = await response.Content.ReadAsStringAsync();
  
  // TODO: Deserialize responseBody and build a new IEnumerable<Customer>
}

Json: Json:

{
    "nextRecords": "\\customers\\123",
    "customers": [
       {"name": "John Doe"},
       {"name": "Mary Doe"}
    ]
}

From sample JSON the following models are derived.从样本 JSON 中导出以下模型。

public class RootObject {
    public string nextRecords { get; set; }
    public IList<Customer> customers { get; set; }
}

public class Customer {
    public string name { get; set; }
}

Getting the result can be done using获取结果可以使用

HttpClient client = new HttpClient();
async Task<IEnumerable<Customer>> GetCustomers(string url) {
    var result = new List<Customer>();
    do {
        var response = await client.GetAsync(url);

        response.EnsureSuccessStatusCode();

        var body = await response.Content.ReadAsAsync<RootObject>();

        result.AddRange(body.customers);

        url = body.nextRecords;
    } while(!string.IsNullOrWhitespace(url));

    return result;        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM