【发布时间】: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是货币代码,例如AUD和Value是另一个对象。