user13468285
user13468285

Reputation:

API call structure in C#

I am a beginner at using C# and I am having a bit of a problem correctly consuming an API, I can make the API a JSON string and view it but that isint of much use to me, so basically I am trying to create a object from a class I created and I want to parse the JSON data I got into the object so I can do more things with it, but I am having problems with structuring my class to fit the data when it gets parsed. If you could help that would be fantastic.

//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"
}
]

Basically I want to know how I can create a post for every object in my API call response and add them to a list or dictionary to be able to consume it better.

Upvotes: 2

Views: 666

Answers (1)

Andy
Andy

Reputation: 13517

The issue you are having is that the data structure of the JSON is an array. So if you use Post[] as your generic type, it works fine:

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[]>();
    }
}

I call it as so:

var resp = await MakeRequestAsync();
foreach(var r in resp)
{
    Console.WriteLine($"Title: {r.Title}");
}

And it outputs as you'd expect:

output

Upvotes: 1

Related Questions