如何在C#中从JSON获取密钥

时间:2016-07-12 05:34:11

标签: c# json api

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"}

我想从中获取密钥列表。 例如。 list应返回所有值,如DKK,EUR,GBP。 需要C#代码来反序列化JSON。

我可以从JSON获取值,但不能获取键。

1 个答案:

答案 0 :(得分:3)

您可以创建与您的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 Package(右键单击项目&gt;经理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