Nested Json Problem how can ı get this data?

Viewed 132

I am trying to get COVID-19 data with the API but I have a problem like this

Here is my code:

var deserial = new JsonDeserializer();
            var client = new RestClient("https://api.thevirustracker.com/free-api?countryTotals=ALL");
            var request = new RestRequest(Method.GET);
            request.AddHeader("content-type", "application/json");
            var response = client.Execute(request);
            var output = deserial.Deserialize<Dictionary<string, string>>(response);
            var data = output["countryitems"];
            var allData = JsonConvert.DeserializeObject<List<CountryItemViewModel>>(data);

My CountryItemViewModel :

public class CountryItemModelView
{
    [JsonProperty("ourid")]
    public long Ourid { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("source")]
    public Uri Source { get; set; }

    [JsonProperty("total_cases")]
    public long TotalCases { get; set; }

    [JsonProperty("total_recovered")]
    public long TotalRecovered { get; set; }

    [JsonProperty("total_unresolved")]
    public long TotalUnresolved { get; set; }

    [JsonProperty("total_deaths")]
    public long TotalDeaths { get; set; }

    [JsonProperty("total_new_cases_today")]
    public long TotalNewCasesToday { get; set; }

    [JsonProperty("total_new_deaths_today")]
    public long TotalNewDeathsToday { get; set; }

    [JsonProperty("total_active_cases")]
    public long TotalActiveCases { get; set; }

    [JsonProperty("total_serious_cases")]
    public long TotalSeriousCases { get; set; }
}

I can take the necessary part, but I can't bring the rest.

1 Answers

You can declare additional class:

public class Data
{
    [JsonProperty("sitedata")]
    public Sitedatum[] Sitedata { get; set; }

    [JsonProperty("countryitems")]
    public Dictionary<string, object>[] Countryitems { get; set; }
}



public class Sitedatum
{
    [JsonProperty("info")]
    public Info Info { get; set; }
}

public class Info
{
    [JsonProperty("source")]
    public Uri Source { get; set; }
}

And deserialize as follow. Notice the JSON returned from the API has a key/value "stat": "ok" which I discard it:

var client = new RestClient("https://api.thevirustracker.com/free-api?countryTotals=ALL");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
var response = client.Execute(request);
var output = JsonConvert.DeserializeObject<Data>(response.Content);

var counteries = new List<CountryItemModelView>();

foreach(var item in output.Countryitems[0])
{
    if(item.Key != "stat")
    {
        var value = item.Value.ToString();
        counteries.Add(JsonConvert.DeserializeObject<CountryItemModelView>(value));
    }
}
Related