Skip to content

How to Use JSON In C# With REST API Call

JSON (JavaScript Object Notation) is one of the most widely used format to store and transfer data. This storage medium is becoming more popular due to its simplicity, especially for web applications. In this tutorial, We will make a C# call rest api json example (and running C# program) to get Weather info by using a REST API.

You may get complete GitHub code to run in your system.

C# call rest api json example

What We Need?

We have made C# coding in Visual Studio 2022 by using .NET library. JSON library recently added to .NET and made programming fairly simple. Alternatively you can use Newtonsoft or json2csharp. Both of them are great libraries but We preferred native .NET library.

We are assuming that you have installed Visual Studio. If you have not installed, get and install it first. Community version is free and it is a great starting point, not only for C# but also for C++, Java, Python and many more.

In this tutorial, We will use Open-Meteo API to get up to date weather information. Many API provider requires subscription and API KEY. But Open-Meteo not requiring a key, at least for basic operations. They provide an unique URL for every location. We will use that URL and Open-Meteo provide the weather data in JSON format.

Let’s Start Coding!

First of all, We need to include JSON file retrieval and data extraction libraries.

using System.Net.Http.Json;
using System.Text.Json.Serialization;

Now, it is time to build JSON data class. Before that, you need to know structure of JSON data. In this example, We will use Open-Meteo current weather API data (https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true)

Look at our sample data :

open meteo current weather json data

Some data (latitude, longitude etc.) presented at Root level and some (current_weather\temperature etc.) at the nested object.

We can build our class now:

   public class City
    {
        public float Latitude { get; set; }

        public float Longitude { get; set; }

        [JsonPropertyName("current_weather")]
        public CurrentWeather? CurrentWeather { get; set; }
       
    }

For test purposes, We did not include all values. Only Latitude and Longitude at Root level. Current_weather is at the nested object and require extra coding.

 public class CurrentWeather
    {
        [JsonPropertyName("temperature")]
        public double Temperature { get; set; }

        [JsonPropertyName("windspeed")]
        public double Windspeed { get; set; }

        [JsonPropertyName("winddirection")]
        public double Winddirection { get; set; }

        [JsonPropertyName("weathercode")]
        public int Weathercode { get; set; }

        [JsonPropertyName("time")]
        public string? Time { get; set; }
    }

Main Program to Parse JSON in C#

Rest is relatively simple.

First We define JSON API url address to parse (BaseAddress).

Next step is to fill our class: City. // (City? city = await client.GetFromJsonAsync<City>(“”);)

At the end show JSON data to console.

Notice the difference between Root values and Nested Object values are how displayed.

public class Program
    {
        public static async Task Main()
        {
            using HttpClient client = new()
            {
                BaseAddress = new Uri("https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true")
            };

            // Get Json Weather information.
            City? city = await client.GetFromJsonAsync<City>("");
            


            Console.WriteLine($"Latitude: {city?.Latitude}");
            Console.WriteLine($"Longitude: {city?.Longitude}");
            Console.WriteLine($"Temperature: {city?.CurrentWeather.Temperature}");
            Console.WriteLine($"WindSpeed: {city?.CurrentWeather.Windspeed}");


        }
    }

This is our output!

Latitude: 52,52
Longitude: 13,419998
Temperature: 2,5
WindSpeed: 6
       

Get Complete Code From GitHub

You can get and run complete code from GitHub free of Charge!

https://github.com/pairmem/weather.git

Summary

In this tutorial We have learned how to make a API REST call and parse JSON data from remote API server by using C# and .NET. This is actually easy and you can use this method for many API applications.

Leave a Reply

Your email address will not be published. Required fields are marked *