3

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...

1
  • You may find a sample GitHub repository on my answer and open an issue. Commented Mar 21, 2020 at 22:25

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

@faithyildizhan => I have to grab the data and insert into my database, so I have ended up using your solution with slightly modification. I have made another class "Total" which I use to map the data from CovidResult so I can use the context and savechanges. For example. I use result.Confirmed = Convert.ToInt32(total.Confirmed.Value); and son on for other fields and last _context.add(total); _context.SaveChanges();
@user2160310 If you are able to share the source code then you can fork and create a pull request. People may use it. If not, still no problem : )
3

Your modal should be

public class Total
{
    public Confirmed confirmed { get; set; }
    public Recovered recovered { get; set; }
    public Deaths deaths { get; set; }
    public string dailySummary { get; set; }
    public DailyTimeSeries dailyTimeSeries { get; set; }
    public string image { get; set; }
    public string source { get; set; }
    public string countries { get; set; }
    public CountryDetail countryDetail { get; set; }
    public DateTime lastUpdate { get; set; }
}

public class Confirmed
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class Recovered
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class Deaths
{
    public int value { get; set; }
    public string detail { get; set; }
}

public class DailyTimeSeries
{
    public string pattern { get; set; }
    public string example { get; set; }
}

public class CountryDetail
{
    public string pattern { get; set; }
    public string example { get; set; }
}

If stringResult has an actual value all you have to do is:

JsonConvert.DeserializeObject<Total>(stringResult);

Also when in doubt about the modal you can always use http://json2csharp.com/

Comments

1

I suggest you to use JSon.NET aka Newtonsoft. You can add it from nuget package manager. Here is the code to map incoming json data to your custom class Total. just add your class contructor which will take json data as argument which is typeof string, and I added one method to make code shorter

public class Total {

    public Total(string json) {
        JObject jObject = JObject.Parse(json);
        Confirmed = GetStringFromJToken(jObject, "confirmed");
        Recovered = GetStringFromJToken(jObject, "recovered");
        Deaths = GetStringFromJToken(jObject, "deaths");

        LastUpdated = (string)jObject["lastUpdate"];
    }

    private string GetStringFromJToken(JObject jObject, string key) {
        JToken keyToken = jObject[key];
        return (string)keyToken["value"];
    }

    [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; }
}

2 Comments

I am having difficulties in saving the data using EF. My dbset context looks like this: public DbSet<Total> Totals { get; set; } When I use it like this: Total myTotal = new Total(stringResult); _context.Add(myTotal); _context.SaveChanges(); And I get this error: InvalidOperationException: No suitable constructor found for entity type 'Total'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'json' in 'Total(string json)'.
I think adding overloaded constructor in Total class should solve that, you had to do like this: Public Total() {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.