Delete

Are you sure you want to delete this?

Info


Title
How to get JSON from an API and Process that Data
Content
<div class="row"> <div class="container"> <div class="col-md-12"> <p>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.</p> <p>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.</p> <h2>Create a new C# Console Application</h2> <ol> <li>Open Visual Studio 2022.</li> <li>Select <b>Create a new project</b>.<br> <img src="/images/articles/JSON-api/1.jpeg" alt="Create new Console Application in Visual Studio" class="img-thumbnail rounded"> </li> <li>Select <b>Console App</b> and then click <b>Next</b>.<br> <img src="/images/articles/JSON-api/2.jpeg" alt="Select Console App in Visual Studio" class="img-thumbnail rounded"> </li> <li>In the Project Name field, type <b>MyJsonApiTutorial</b> and then click <b>Next</b>.<br> <img src="/images/articles/JSON-api/3.jpeg" alt="Type in project name for Console App in Visual Studio" class="img-thumbnail rounded"> </li> <li>In the Framework field, select <b>.NET 6.0 (Long Term Support)</b> and then click <b>Create</b>.<br> <img src="/images/articles/JSON-api/4.jpeg" alt="Select type of .NET framework to be used for the Console App in Visual Studio" class="img-thumbnail rounded"> </li> <li>Press the <b>F5</b> key on your keyboard to test if the default application works.<br> <img src="/images/articles/JSON-api/5.jpeg" alt="Default output of Console App" class="img-thumbnail rounded"> </li> <li>Press the <b>Spacebar </b>key on your keyboard to stop the Console Application.<br> </li> <li>If not open already, open the file <b>Program.cs</b> in Visual Studio.<br> </li> <li>Replace the existing code with the following code:<br> <div class="overflow-auto"> <code> namespace MyJsonApiTutorial<br> {<br> internal class Program<br> { <br> static void Main(string[] args)<br> {<br> Console.WriteLine("Hello, from MyJsonApiTutorial");<br> Console.ReadKey();<br> }<br> }<br> } </code> </div> </li> <li>Press they <b>F5</b> key to test if the modified application works.<br> <img src="/images/articles/JSON-api/6.jpeg" alt="Default output of Console App" class="img-thumbnail rounded"> </li> </ol> <br> <h2>Get Sample JSON Data to create Classes</h2> <ol> <li>In your Internet browser, open the website <b>https://randomuser.me/api/</b>. </li> <li>Copy the sample JSON that is shown in the Internet brower.<br> <p><i><b>Note:</b>Your data sample will be different than that shown in the image. New data is created each time you open the web page.</i></p><img src="/images/articles/JSON-api/7.jpeg" alt="Sample JSON data" class="img-thumbnail rounded"> </li> <li>Open the website: https://json2csharp.com/.<br> </li> <li>Make sure that the button JSON to C# is selected. See image.<br> </li> <li>Paste the JSON data in the ‘JSON’ column on the left-hand side.<br> <img src="/images/articles/JSON-api/8.jpeg" alt="Open website json2csharp" class="img-thumbnail rounded"> </li> <li>Click the <b>Convert</b> button.<br> </li> <li>Copy the content in the right-hand column.<br> <img src="/images/articles/JSON-api/9.jpeg" alt="Class content" class="img-thumbnail rounded"> </li> <li>in Visual Studio, right-click the project name to select <b>Add &gt; Class</b>.<br> <img src="/images/articles/JSON-api/14.jpeg" alt="Add Class" class="img-thumbnail rounded"> </li> <li>In the Name field, type <i>User.cs</i> and click <b>Add</b>.<br> <img src="/images/articles/JSON-api/10.jpeg" alt="Add Class dialog" class="img-thumbnail rounded"> </li> <li>In the User.cs file remove the User class.<br> <img src="/images/articles/JSON-api/11.jpeg" alt="Remove User Class" class="img-thumbnail rounded"> </li> <li>Paste the Class data in User.cs<br> <img src="/images/articles/JSON-api/12.jpeg" alt="Paste generated Class content in class" class="img-thumbnail rounded"> </li> <li>Copy the following <b>GetJson()</b> Method to file Program.cs underneath the Main method.<br> <div class="overflow-auto"> <code> private static void GetJson()<br> {<br> using HttpClient client = new HttpClient();<br> var response = client.GetAsync("https://randomuser.me/api/").Result;<br> UserRoot? userData;<br> var jsonString = string.Empty; <br> if (response.IsSuccessStatusCode) <br> { jsonString = response.Content.ReadAsStringAsync().Result;<br> Object? k = JsonConvert.DeserializeObject&lt;object&gt;(jsonString);<br> userData = JsonConvert.DeserializeObject&lt;UserRoot&gt;(jsonString);<br> foreach (var item in userData.results)<br> {<br> Console.WriteLine($"The first and last name is {item.name.first} {item.name.last}.");<br> Console.WriteLine($"Congratulations! You processed a JSON file.");<br> }<br> }<br> else<br> {<br> Console.WriteLine($"No Success Status Code.\n{response.StatusCode}");<br> Console.ReadKey();<br> return;<br> }<br> }<br> </code> </div> </li> <li>Put the cursor on the text <b>JsonConvert</b> and press <b>Alt+Enter</b>.<br> <img src="/images/articles/JSON-api/13.jpeg" alt="Fix missing packages" class="img-thumbnail rounded"> </li> <li>In the context menu select <b>Install package 'Newtonsoft.Json' &gt; Find and install latest version</b>.<br> <p><i><b>Note:</b>The red squickly underneath JsonConvert should disappear.</i></p> </li> <li>Update the&nbsp;<b>Main</b> method with the following content:<br> <div class="overflow-auto"> <code> static void Main(string[] args)<br> {<br> GetJson();<br> Console.ReadKey(); <br> }<br> </code> </div> </li> <li>Press <b>F5</b> to test the project.<br> <img src="/images/articles/JSON-api/15.jpeg" alt="Application output" class="img-thumbnail rounded"> </li> </ol> <p>This is the end of this tutorial. I hope you find this useful and wish you good luck coding your projects.</p> <h3>Need a Freelance .NET developer?</h3> <p>If you are in need of a freelance .NET developer, feel free to contact me by email: info {at} schoutentranslation.nl.</p> </div> </div> </div>
Excerpt
CoverImagePath
/images/dotnetcode.jpg
Created
8-11-2023 12:42:14
Updated
8-11-2023 16:46:16
Views
4085
Public
| Back to List