In this knowledge share I would like to show you how you can collect JSON from an external API, and then create C# classes and a Root object class that represent the JSON structure to process the data.
I am using Visual Studio 2022 for this. The first section describes how to set up a console project. The second section shows the code that is needed to create a working example to collect and process JSON data from an API.
namespace MyJsonApiTutorial
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, from MyJsonApiTutorial");
Console.ReadKey();
}
}
}
Note:Your data sample will be different than that shown in the image. New data is created each time you open the web page.
private static void GetJson()
{
using HttpClient client = new HttpClient();
var response = client.GetAsync("https://randomuser.me/api/").Result;
UserRoot? userData;
var jsonString = string.Empty;
if (response.IsSuccessStatusCode)
{
jsonString = response.Content.ReadAsStringAsync().Result;
Object? k = JsonConvert.DeserializeObject<object>(jsonString);
userData = JsonConvert.DeserializeObject<UserRoot>(jsonString);
foreach (var item in userData.results)
{
Console.WriteLine($"The first and last name is {item.name.first} {item.name.last}.");
Console.WriteLine($"Congratulations! You processed a JSON file.");
}
}
else
{
Console.WriteLine($"No Success Status Code.\n{response.StatusCode}");
Console.ReadKey();
return;
}
}
Note:The red squickly underneath JsonConvert should disappear.
static void Main(string[] args)
{
GetJson();
Console.ReadKey();
}
This is the end of this tutorial. I hope you find this useful and wish you good luck coding your projects.
If you are in need of a freelance .NET developer, feel free to contact me by email: info {at} schoutentranslation.nl.
Created: 8-11-2023 - Last Update: 8-11-2023 - Views: 3503