json - 如何从字典中获取数据(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”等字典中获取每个元素的值?
解决方案
你可以这样做:
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;
}
推荐阅读
- javascript - 将下载 url 分配给变量 firestore
- python - 将列表中的值输入到 Pandas 数据框中
- asp.net-core - 在按钮单击 Mvc Core 时传递模型子集
- assembly - 添加后的意外行为
- c++ - 为什么使用 getline 后 cin 没有获取缓冲区数据?
- javascript - 尝试运行一个导入失败的笑话测试,可能与猫鼬有关
- amazon-web-services - 使用每个 terraform 在单独的 AZ 中创建不同的 EC2 实例
- snowflake-cloud-data-platform - 列出雪花中特定表中具有数据类型的所有列
- c++ - 从 std::vector 复制到推力::device_vector 时出现未处理的异常
- php - 在 WooCommerce 结帐中为特定产品类别制作所需的订单注释