我有一个Task方法,该方法调用一个远程API,该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);
}
}
User.cs-
public class User
{
[Key]
public int UserId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
UserList.cs-
public class UserList
{
public List<User> Results { get; set; }
}
答案 0 :(得分:1)
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 after,例如:
UserList test = await GetUser();
答案 1 :(得分:1)
the return has to be a Task<List<User>>, not just List<User>
答案 2 :(得分:0)
// 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
}