如何用c#查询JSON数组,获取特定属性

本文关键字:获取 属性 数组 何用 查询 JSON | 更新日期: 2023-09-27 18:15:48

我需要在运行时动态地获得JSON属性。JSON看起来像这样:

{
  "timestamp": 1369828868,
  "base": "USD",
  "rates": {
    "AED": 3.673416,
    "AFN": 54.135233,
    "ALL": 108.828249,
    "AMD": 419.878748,
    "ANG": 1.788475,
    "AOA": 96.154668,
    "XDR": 0.66935,
    "XOF": 507.521247,
    "XPF": 92.277412,
    "YER": 214.913206,
    "ZAR": 9.769538,
    "ZMK": 5227.108333,
    "ZMW": 5.316935,
    "ZWL": 322.322775
  }
}

我需要从上面的"Rates"数组中获取货币。我需要一些帮助弄清楚如何查询JSON结构。我在用Newtonsoft

我不想避免做的是在c#中硬编码一个switch语句,所以我做不想这样做:

var json = JsonConvert.DeserializeObject(jsonString) as dynamic;
switch (currencyPair.QuoteCurrencyCode)
{
    case "EUR":
        exchangeRate = json.rates.EUR;
        break;
    case "CNY":
        exchangeRate = json.rates.CNY;
        break;
    case "NZD":
        exchangeRate = json.rates.NZD;
        break;
    case "USD":
        exchangeRate = json.rates.USD;
        break;
    case "GBP":
        exchangeRate = json.rates.GBP;
        break;
    case "HKD":
        exchangeRate = json.rates.HKD;
        break;
    case "JPY":
        exchangeRate = json.rates.JPY;
        break;
    case "CAD":
        exchangeRate = json.rates.CAD;
        break;
    default:
        throw new Exception("Unsupported to currency: " + currencyPair.QuoteCurrencyCode);
}

如何用c#查询JSON数组,获取特定属性

您可以使用Json创建字典。净

var jObj = JObject.Parse(json);
var rates = jObj["rates"].Children().Cast<JProperty>()
            .ToDictionary(p => p.Name, p => (double)p.Value);
//A single statement instead of switch
var exchangeRate = rates[currencyPair.QuoteCurrencyCode];

可以使用Json。Net来做这个:示例:

            string json = @"{
  ""timestamp"": 1369828868,
  ""base"": ""USD"",
  ""rates"": {
    ""AED"": 3.673416,
    ""AFN"": 54.135233,
    ""ALL"": 108.828249,
    ""AMD"": 419.878748,
    ""ANG"": 1.788475,
    ""AOA"": 96.154668,
    ""XDR"": 0.66935,
    ""XOF"": 507.521247,
    ""XPF"": 92.277412,
    ""YER"": 214.913206,
    ""ZAR"": 9.769538,
    ""ZMK"": 5227.108333,
    ""ZMW"": 5.316935,
    ""ZWL"": 322.322775
  }
}";
            dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            if (data.@base == "USD")
            {
            }
// Get the rates
foreach (var rate in data.rates) { };