【问题标题】:How to query JSON array with C#, For a specific Property如何使用 C# 查询 JSON 数组,针对特定属性
【发布时间】:2013-05-29 12:46:42
【问题描述】:

我需要在运行时动态获取 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
  }
}

我需要从上面的“汇率”数组中获取一种货币。我需要一些帮助来弄清楚如何查询 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# .net json parsing


    【解决方案1】:

    你可以创建一个字典,使用Json.Net

    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];
    

    【讨论】:

    • 我不得不用 JArray 替换 JObject。我尝试使用此解决方案,但在我的场景中,我收到一组记录并且没有根/包装器对象。
    【解决方案2】:

    您可以使用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) { };
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多