c# - C#中的API调用结构

标签 c# asp.net .net api

大家好,我是使用 c# 的初学者,我在正确使用 api 时遇到了一些问题,我可以将 api 设为 json 字符串并查看它,但这对我来说没什么用,所以基本上我正在尝试创建一个来自我创建的类的对象,我想解析我进入该对象的 json 数据,这样我就可以用它做更多的事情,但是我在构建我的类以适应解析数据时遇到问题..如果你可以帮助那将是太棒了

//my function to make the api call
static async Task<Post> MakeRequest()
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");

            if (response.IsSuccessStatusCode)
            {
                Post res = await response.Content.ReadAsAsync<Post>();

                return res;
            } else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
//my class im trying to parse the data into
public class Post
    {
        public string Title { get; set; }
        public string Body { get; set; }
    }
//example of the api call response
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
qui aperiam non debitis possimus qui neque nisi nulla"
}
]
基本上,我想知道如何为 api 调用响应中的每个对象创建一个帖子,并将它们添加到列表或字典中,以便更好地使用它。

最佳答案

您遇到的问题是 JSON 的数据结构是一个数组。所以如果你使用 Post[]作为您的通用类型,它工作正常:

private static async Task<Post[]> MakeRequestAsync()
{
    using (var msg = new HttpRequestMessage(HttpMethod.Get,
        new Uri("https://jsonplaceholder.typicode.com/posts")))
    using (var resp = await _client.SendAsync(msg))
    {
        resp.EnsureSuccessStatusCode();
        // Using the System.Net.Http.HttpClientExtensions method:
        return await resp.Content.ReadAsAsync<Post[]>();
        // Using the System.Net.Http.Json.HttpClientJsonExtensions method:
        // return await resp.Content.ReadFromJsonAsync<Post[]>();
    }
}
我这样称呼它:
var resp = await MakeRequestAsync();
foreach(var r in resp)
{
    Console.WriteLine($"Title: {r.Title}");
}
它会按您的预期输出:
output

关于c# - C#中的API调用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63443310/

相关文章:

c# - 在 Web API 2 中创建更新方法

c# - 标签单击事件以在 C# 中的新线程上运行

.net - dotfuscator并行优化?

c# - 是否可以在用户不可见的情况下使用表单?

c# - 如何使用数据库中的图像 URL 并显示在 Razor 页面中?

c# - 在 C# 中使用 LINQ 将 XML 元素转换为元组

c# - 在 ASP.NET MVC 中填充 DropDownList

asp.net - xVal 和正则表达式匹配

c# - 如何在母版页的内容页中设置默认焦点

c# - Windows自定义控件如何实现数据绑定(bind)?