[英]Return list from static async Task method
我有一个调用远程 API 的任务方法,该方法采用返回的 JSON 并将数据转换为 C# 对象,并在控制台上显示数据。 我希望这个方法也能返回列表,以便我可以在其他地方使用它,有人可以告诉我当我将方法签名更改为列表类型时我如何不断出错,所有回复都表示赞赏! -
// asynchronous retrieve data from api
public static async Task GetUser()
{
//baseUrl
string baseUrl = "http://pokeapi.co/api/v2/pokemon/";
try
{
// HttpClient implements a IDisposable interface
using (HttpClient client = new HttpClient())
//initiate Get Request
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
//convert response to c# object
using (HttpContent content = res.Content)
{
//convert data content to string using await
var data = await content.ReadAsStringAsync();
//If the data is not null, parse(deserialize) the data to a C# object
if (data != null)
{
var result = JsonConvert.DeserializeObject<UserList>(data);
foreach (var u in result.Results)
{
Console.WriteLine("Name: {0} | Url: {1}", u.Name, u.Url);
}
}
else
{
Console.WriteLine("No returned data");
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
// asynchronous retrieve data from api
public static async Task<List<User>> GetUser()
{
//Connect to the webservice and get the data
//Parse the data into a list of Users
var myList = parseResultJsonFromServer(serverResult);
//myList is of type List<User> and ready to be returned
return myList
}
public static async Task<UserList> GetUser()
{
//baseUrl
string baseUrl = "http://pokeapi.co/api/v2/pokemon/";
try
{
// HttpClient implements a IDisposable interface
using (HttpClient client = new HttpClient())
{
//initiate Get Request
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
//convert response to c# object
using (HttpContent content = res.Content)
{
//convert data content to string using await
var data = await content.ReadAsStringAsync();
//If the data is not null, parse(deserialize) the data to a C# object
if (data != null)
{
return JsonConvert.DeserializeObject<UserList>(data);
}
else
{
return null;
}
}
}
}
}
catch (Exception exception)
{
return null;
}
}
您可以在之后使用 await ,如下所示:
UserList test = await GetUser();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.