我是.NET Core的新手,正在尝试解决问题;练习如何使用Flurl使用API。使用此端点https://jsonplaceholder.typicode.com/posts返回JSON数组,我尝试了以下代码,但是列表包含无法转换的动态。谁能建议如何将动态内容转换为适当的post对象?
public class PostsApiClient
{
public async Task<IEnumerable<PostInput>> GetPosts()
{
var response = await "https://jsonplaceholder.typicode.com/posts".GetJsonListAsync();
IEnumerable<Post> listOfPosts = response.Select(post => new Post
{
Title = post.Title,
Body = post.Body
});
return listOfPosts;
}
public class Post
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
GetJsonListAsync
是专门为返回动态列表而设计的。没有专门用于列表的类型化(通用)等效项,但您需要做的就是向GetJsonAsync
提供一个集合类型。在您的情况下,这应该可以工作:
public async Task<IEnumerable<Post>> GetPosts()
{
return await url.GetJsonAsync<Post[]>();
}