如何在 C# 中从 JSON 获取密钥
本文关键字:JSON 获取 密钥 中从 | 更新日期: 2023-09-27 17:56:22
JSON :
{"From":
{"CHF":{"Rate":0.91640105,"AsAtDate":"2016-04-19T00:00:00"},
"DKK":{"Rate":0.13437824,"AsAtDate":"2016-04-19T00:00:00"},
"EUR":{"Rate":1.0,"AsAtDate":"2016-04-19T00:00:00"},
"GBP":{"Rate":1.25985769,"AsAtDate":"2016-04-19T00:00:00"},
"PLN":{"Rate":0.23213581,"AsAtDate":"2016-04-19T00:00:00"},
"RON":{"Rate":0.22338218,"AsAtDate":"2016-04-19T00:00:00"},
"SEK":{"Rate":0.10868521,"AsAtDate":"2016-04-19T00:00:00"}},
"To":"EUR","RequestedDate":"2016-07-08T00:00:00"}
我想从下获取键列表。例如。列表应返回键的所有值,如丹麦克朗、欧元、英镑。反序列化 JSON 需要 C# 代码。
我能够从 JSON 中获取值,但不能从键中获取值。
您可以创建与 json 格式匹配的类,然后读取密钥:
public class CurrecyConversion
{
public Dictionary<string, CurrencyRate> From { set; get; }
public string To { set; get; }
public DateTime RequestedDate { set; get; }
}
public class CurrencyRate
{
public decimal Rate { set; get; }
public DateTime AsAtDate { set; get; }
}
您需要下载此 Nuget 包(右键单击项目>管理器 Nuget 包)
用法:
CurrecyConversion result = Newtonsoft.Json.JsonConvert.
DeserializeObject<CurrecyConversion>(jsonText);
List<string> keys = result.From.Keys.ToList();
foreach (var key in keys)
Console.WriteLine(key);
结果:
CHF
DKK
EUR
GBP
PLN
RON
SEK