Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Import JSON from external API

I am new to both .NET Core home somebody can guide me through this.

I need to make a request to this url and save the data into database: url: https://covid19.mathdro.id/api

JSON output looks like this:

{"confirmed":{"value":303001,"detail":"https://covid19.mathdro.id/api/confirmed"},"recovered":{"value":91669,"detail":"https://covid19.mathdro.id/api/recovered"},"deaths":{"value":12762,"detail":"https://covid19.mathdro.id/api/deaths"},"dailySummary":"https://covid19.mathdro.id/api/daily","dailyTimeSeries":{"pattern":"https://covid19.mathdro.id/api/daily/[dateString]","example":"https://covid19.mathdro.id/api/daily/2-14-2020"},"image":"https://covid19.mathdro.id/api/og","source":"https://github.com/mathdroid/covid19","countries":"https://covid19.mathdro.id/api/countries","countryDetail":{"pattern":"https://covid19.mathdro.id/api/countries/[country]","example":"https://covid19.mathdro.id/api/countries/USA"},"lastUpdate":"2020-03-21T20:13:21.000Z"}

Model: Totals

public class Total
{
    [Key]
    public int Id { get; set; }
    [Column(TypeName = "int")]
    [Required]
    public string Confirmed { get; set; }
    [Column(TypeName = "int")]
    [Required]
    public string Recovered { get; set; }
    [Column(TypeName = "int")]
    [Required]
    public string Deaths { get; set; }
    [Column(TypeName = "datetime2")]
    [Required]
    public string LastUpdated { get; set; }
}

My import model:

client.BaseAddress = new Uri("https://covid19.mathdro.id/api");
var response = await client.GetAsync($"");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();

I am stuck from here and cant continue. How do I fetch the data, I need only: confirmed, recovered, deaths and lastUpdate

Pls. anybody help here...

like image 245
Danny Web Avatar asked Dec 04 '25 03:12

Danny Web


1 Answers

You need to cast JSON to a Class Object. You may get your data like this by using NewtonSoft.Json

using (var client = new HttpClient())
{
  string url = string.Format("https://covid19.mathdro.id/api");
  var response = client.GetAsync(url).Result;

  string responseAsString = await response.Content.ReadAsStringAsync();
  result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}

public class CovidResult
{
   [JsonProperty("confirmed")]
   public ValueModel Confirmed { get; set; }
   [JsonProperty("recovered")]
   public ValueModel Recovered { get; set; }
   [JsonProperty("deaths")]
   public ValueModel Deaths { get; set; }
}

public class ValueModel
{
   [JsonProperty("value")]
   public int Value { get; set; }
}

You may fork or download this repo: https://github.com/fatihyildizhan/CoronaParser

like image 144
fatihyildizhan Avatar answered Dec 05 '25 19:12

fatihyildizhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!