(Json 反序列化对象),json,json.net,asp.net-core-mvc"/>

首页 > 解决方案 > 如何从字典中获取数据(Json 反序列化对象)

问题描述

我使用 Newtonsoft 反序列化了动态 Json。JSON 是复杂且动态的。

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

为了克服数据类型问题,我使用了动态对象

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

Up to This 效果很好。现在我正在尝试从这个动态字典中获取数据

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

我将数据作为字典计数 (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}}]}

如何从“values.list.country”等字典中获取每个元素的值?

Visual Studio 调试 - 输出

标签: jsonjson.netasp.net-core-mvc

解决方案


你可以这样做:

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();

数据结构如下:

在此处输入图像描述

然后,您可以使用 foreach 循环来获取指定值:

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

推荐阅读