C# c语言中的Api调用结构#

C# c语言中的Api调用结构#,c#,asp.net,.net,api,C#,Asp.net,.net,Api,大家好,我是c#的初学者,我在正确使用api时遇到了一些问题,我可以将api设置为json字符串并查看它,但这对我没有多大用处,所以基本上我正在尝试从我创建的类创建一个对象,我想解析进入该对象的json数据,以便我可以用它做更多的事情,但是我在构造类以适应解析数据时遇到的问题。。如果你能帮忙,那就太好了 //my function to make the api call static async Task<Post> MakeRequest() {

大家好,我是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);
            }
        }

基本上,我想知道如何为api调用响应中的每个对象创建一个post,并将它们添加到列表或字典中,以便更好地使用它。

您遇到的问题是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[]>();
    }
}
它的输出正如您所期望的:


JSON结构是一个数组,因此将读取更改为:
response.Content.ReadAsAsync()
。当然,您可以反序列化阵列。最好弄清楚应用程序在哪里配置为使用Newtonsoft。Json@AluanHaddad--由于新的
System.text.Json
ReadAsAsync
名为
ReadFromJsonAsync
,因此我去掉了那行文本,因此应该推断出它。谢谢你的澄清,这很有趣。但是,仍然可以配置要使用的反序列化程序。@AluanHaddad——据我所见,您可以选择其中一个。我添加了一些文本,以澄清您应该根据当前安装的扩展调用哪个方法。我完全同意。我只是在想,有人读了这篇文章,却没有看到对newtonsoft的依赖,也没有看到它的注册和困惑。我仍然投票赞成这个答案
//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"
}
]
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}");
}