Search code examples
jsonjson.netasp.net-core-mvc

How to fetch data from Dictionary<string, dynamic> (Json DeserializeObject)


I have Deserialized dynamic Json using Newtonsoft. The JSON is complex and dynamic.

{
"last_updated": " ",
"regions": {
"antarctica": {
        "name": "Antarctica",
        "totals": [],
        "list": [
            "aq",
            "bv",
            "gs",
            "tf",
            "hm"
        ]
    },
"world": {
        "name" : "",
        "totals": {
            "confirmed": 250566,
            "daily_confirmed": 0,
            "recovered": 202098,
            "deaths": 35205,
            "daily_deaths": 0,
            "critical": 676,
            "tests": 7249844
        },
        "list": [
            {
                "country": "Italy",
                "country_code": "it",
                "state": "Lombardy",
                "confirmed": 85775,
                "deaths": 15662,
                "critical": 231,
                "recovered": 231,
                "tests": 43442,
                "daily_confirmed": -1,
                "daily_deaths": -1
            }, and so on ..
       

To overcome the data type issue I have used the dynamic objects

        [JsonTypedExtensionData]
    public Dictionary<string, dynamic> items { get; set; }    

Up to This works well. Now I am trying to fetch the data out of this dynamic Dictionary

var report = await GetCountryReport();
        Dictionary<string, dynamic> Dict = report.regions.results["world"].items;

I'm getting data as Dict Count (2)

[0] = {[list, {[ {"country": "Italy","confirmed": 4149,"deaths": 55,"recovered": 2916,"Incidence_Rate": "54.408517127144925","Case-Fatality_Ratio": "1.274822260357931","last_updated": "2020-08-10T22:30:32Z","...
[1] = {[totals, {{"confirmed": 20218306,"recovered": 12814226,"deaths": 737481,"critical": 64743,"tests": 370260493}}]}

How do I fetch the values of each element from the Dictionary like "values.list.country" etc..?

Visual Studio debug - output


Solution

  • You can do it like below:

    var list = Dict.Where(x => x.Key == "list").Select(x => x.Value).SingleOrDefault();
    var data = ((JArray)list).Select(x => new
    {
        country = (string)x["country"],
        state = (string)x["state"],
        confirmed = (int)x["confirmed"]
        //...other properties in list
    }).ToList();
    

    The data structure is like below:

    enter image description here

    Then, you can use a foreach loop to get the specify value:

    foreach(var x in data)
    {
        var country = x.country;
        var state = x.state;
        var confirmed = x.confirmed;
    }