To fetch JSON API response from web and deserialize it to class in C# (NET 6 / 7), next steps are needed:
– Use the HttpClient class to send HTTP requests and receive HTTP responses³.
– Use the JsonSerializer class to deserialize JSON into objects²³.
– Create a class with properties that match the JSON properties you want to deserialize².
Class we already created in previous post Consuming json API in C# application
Here is an example of fetching JSON data response from public web API deserializing it to a ApiResponse class:
It has two methods one for asynchronous and another for synchronous call.
Input parameter is page number to fetch, default is page 1.
using System.Text.Json; namespace YifyReleases.Classes { public class ApiConnector { private static readonly HttpClient client = new HttpClient(); public static async Task<ApiResponse> ProcessReleasesAsync(int pageNo = 1) { var request = new HttpRequestMessage(HttpMethod.Get, $"https://yts.mx/api/v2/list_movies.json?limit=50&page={pageNo}"); request.Headers.Add("User-Agent", ".NET New Releases Fetcher"); var response = await client.SendAsync(request); // Ensure web request was successful response.EnsureSuccessStatusCode(); using var responseStream = await response.Content.ReadAsStreamAsync(); if (responseStream == null) { return new ApiResponse(); } else { return await JsonSerializer.DeserializeAsync<ApiResponse>(responseStream); } } public static ApiResponse ProcessReleases(int pageNo = 1) { var request = new HttpRequestMessage(HttpMethod.Get, $"https://yts.mx/api/v2/list_movies.json?limit=50&page={pageNo}"); request.Headers.Add("User-Agent", ".NET New Releases Fetcher"); var task = client.SendAsync(request); task.Wait(); var response = task.Result; // Ensure web request was successful response.EnsureSuccessStatusCode(); var task2 = response.Content.ReadAsStreamAsync(); task2.Wait(); using var responseStream = task2.Result; if (responseStream == null) { return new ApiResponse(); } else { return JsonSerializer.Deserialize<ApiResponse>(responseStream); } } } }
Method returns ApiResponse class.
See also previous post Consuming json API in C# application – part 2
———————————————————————
(2) How to serialize and deserialize JSON using C# – .NET.
(3) json.net – C# Deserialize json api response – Stack Overflow.