Home > Software engineering >  C# API requests which return a class
C# API requests which return a class

Time:01-11

Hey all (newbie here) I am developing A Xamarin forms application In which I am already making API requests (Code is Down Below), However, the response I am getting back at the moment looks like this:

{
  "result": "success",
  "documentation": "https://www.exchangerate-api.com/docs",
  "terms_of_use": "https://www.exchangerate-api.com/terms",
  "time_last_update_unix": 1673308801,
  "time_last_update_utc": "Tue, 10 Jan 2023 00:00:01  0000",
  "time_next_update_unix": 1673395201,
  "time_next_update_utc": "Wed, 11 Jan 2023 00:00:01  0000",
  "base_code": "EUR",
  "target_code": "GBP",
  "conversion_rate": 0.8803
}

I am Only using the conversion rate variable however in the next API I am hoping to use all this variables are stored in parameters (Class I guess?) called Data, so currently, the class I am using to store the variable which is grabbed from this API response looks like this:

public double conversion_rate { get; set; }

So how would I adapt this code to interpret that data, the response is below (I want the data labeled "actual" in the "intensity" section TIA):

"data": [
    {
      "from": "2023-01-10T19:30Z",
      "to": "2023-01-10T20:00Z",
      "intensity": {
        "forecast": 70,
        "actual": 79,
        "index": "low"
      }
    }
  ]

Ive attempted to find a solution on my own for a while, looked all around and still nothing to see :)

CodePudding user response:

I would create two DTO (data transfer object) classes which contain the properties you're interested in. Once you make the API request, you can map or parse the relevant fields to another object or type.

FYI - you should rename conversion_rate to ConversionRate, which is the standard for property names in C# and then add [JsonPropertyName("conversion_rate")] above the property.

CodePudding user response:

First, you can write the c# class entity based on the json file. Here is the demo and you can refer to.

public class Root
{
    public string result { get; set; }
    public string documentation { get; set; }
    public string terms_of_use { get; set; }
    public int time_last_update_unix { get; set; }
    public string time_last_update_utc { get; set; }
    public int time_next_update_unix { get; set; }
    public string time_next_update_utc { get; set; }
    public string base_code { get; set; }
    public string target_code { get; set; }
    public double conversion_rate { get; set; }
}

Then, you can write the method to deserialize the json file.

using System.Text.Json;

var options = new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var codeRoot = JsonSerializer.Deserialize<Root>(Json, options);
  • Related