Details
Info
- Title
- How to get JSON from an API and Process that Data
- MetaTitle
- Get JSON from API and Process that Data
- MetaDescription
- Get JSON data from an external API and process that data through C# class objects
- MetaKeywords
- Csharp, JSON, API
- PagesUrl
- how-to-collect-json-from-an-api
- Content
-
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.
Create a new C# Console Application
- Open Visual Studio 2022.
- Select Create a new project.
- Select Console App and then click Next.
- In the Project Name field, type MyJsonApiTutorial and then click Next.
- In the Framework field, select .NET 6.0 (Long Term Support) and then click Create.
- Press the F5 key on your keyboard to test if the default application works.
- Press the Spacebar key on your keyboard to stop the Console Application.
- If not open already, open the file Program.cs in Visual Studio.
- Replace the existing code with the following code:
namespace MyJsonApiTutorial
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, from MyJsonApiTutorial");
Console.ReadKey();
}
}
} - Press they F5 key to test if the modified application works.
Get Sample JSON Data to create Classes
- In your Internet browser, open the website https://randomuser.me/api/.
- Copy the sample JSON that is shown in the Internet brower.
Note:Your data sample will be different than that shown in the image. New data is created each time you open the web page.
- Open the website: https://json2csharp.com/.
- Make sure that the button JSON to C# is selected. See image.
- Paste the JSON data in the ‘JSON’ column on the left-hand side.
- Click the Convert button.
- Copy the content in the right-hand column.
- in Visual Studio, right-click the project name to select Add > Class.
- In the Name field, type User.cs and click Add.
- In the User.cs file remove the User class.
- Paste the Class data in User.cs
- Copy the following GetJson() Method to file Program.cs underneath the Main method.
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;
}
}
- Put the cursor on the text JsonConvert and press Alt+Enter.
- In the context menu select Install package 'Newtonsoft.Json' > Find and install latest version.
Note:The red squickly underneath JsonConvert should disappear.
- Update the Main method with the following content:
static void Main(string[] args)
{
GetJson();
Console.ReadKey();
}
- Press F5 to test the project.
This is the end of this tutorial. I hope you find this useful and wish you good luck coding your projects.
Need a Freelance .NET developer?
If you are in need of a freelance .NET developer, feel free to contact me by email: info {at} schoutentranslation.nl.
- Excerpt
- CoverImagePath
- /images/dotnetcode.jpg
- Created
- 8-11-2023 12:42:14
- Updated
- 8-11-2023 16:46:16
- Views
- 1641
- Public