【问题标题】:Flurl: GetJsonListAsync returns list of dynamic objectsFlurl:GetJsonListAsync 返回动态对象列表
【发布时间】:2019-12-11 14:21:53
【问题描述】:

我是 .NET Core 的新手,正在尝试解决问题;练习如何使用 Flurl 使用 API。 使用返回 JSON 数组的端点 https://jsonplaceholder.typicode.com/posts,我尝试了以下代码,但列表包含我无法转换的动态。谁能建议如何将动态转换为适当的帖子对象?

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; }
    }
}

【问题讨论】:

    标签: dynamic .net-core casting flurl


    【解决方案1】:

    GetJsonListAsync 专门用于返回动态列表。没有专门用于列表的类型化(通用)等价物,但您需要做的就是为GetJsonAsync 提供一个集合类型。在您的情况下,这应该有效:

    public async Task<IEnumerable<Post>> GetPosts()
    {
        return await url.GetJsonAsync<Post[]>();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2012-05-09
      • 2019-03-16
      • 1970-01-01
      相关资源
      最近更新 更多