【问题标题】:Json parsing failed but absolute path worksJson 解析失败但绝对路径有效
【发布时间】:2021-08-23 09:30:35
【问题描述】:

我尝试在循环中的表单加载事件中解析来自 web 的 json。 但由于未知原因,我得到了一个例外:

System.InvalidOperationException: '无法访问 Newtonsoft.Json.Linq.JProperty 上的子值。'

但是当我通过绝对路径检查一个单元时 - 它给了我价值。

//var test = (string)ratesjson["Valute"]["AUD"]["CharCode"];

请告诉我我哪里错了。

private string url = "https://www.cbr-xml-daily.ru/daily_json.js";   


private async Task<List<CurrencyRateMap>> GetCurrencyRates()
{
    var list = new List<CurrencyRateMap>();
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(url);
    var result = await response.Content.ReadAsStringAsync();

    var ratesjson = JObject.Parse(result);

    //var test = (string)ratesjson["Valute"]["AUD"]["CharCode"];

    foreach (var x in ratesjson["Valute"])
    {

        CurrencyRateMap crm = new CurrencyRateMap {
            CurrencyCode = (string)x["CharCode"],
            CurrencyRate = (double)x["Value"]
        };
        list.Add(crm);
    }

    return list;
}


private async void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
    CurrentContext.CurrencyRates = await GetCurrencyRates();
}

【问题讨论】:

  • x 转换为 JProperty 然后将其 Value (属性)然后在您的代码中使用此对象而不是 x 或将 var x 更改为 var p 然后添加 var x = ((JProperty)p).Value; ...奖金:使用decimal 而不是double 在其他情况下,IEEE 754 会踢你...
  • 您的代码中没有绝对路径。 ratesjson["Valute"]["AUD"]["CharCode"] 是一个查找调用链。它起作用的事实意味着x 是一个JProperty,其Name 是货币代码,例如AUDValue 是另一个对象。

标签: c# json json.net


【解决方案1】:

循环中的x 是一个具有属性名称的对象,例如AUD 等,CharCodeValue 属性隐藏在该级别之下。但是,将 JSON 解析为实际的 C# 对象会容易得多。它们更容易编写代码并且更安全。例如:

public class Root
{
    public Dictionary<string, CurrencyRateMap> Valute { get; set; }
}

public class CurrencyRateMap
{
    public string Id { get; set; }
    public string NumCode { get; set; }
    public string CharCode { get; set; }
    public double Value { get; set; }
}

现在你可以这样做了:

var ratesjson = JsonConvert.DeserializeObject<Root>(result);

list = ratesjson.Valute.Select(v => v.Value).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2012-05-20
    • 2020-11-29
    • 2016-10-27
    • 2022-01-14
    • 2010-10-03
    相关资源
    最近更新 更多