【发布时间】:2022-11-19 14:16:55
【问题描述】:
我收到以下错误 - System.NullReferenceException: 'Object reference not set to an instance of an object.' 我知道我为什么会收到它 - 我正在解析一些 JSON 不幸的是它在包含键方面不一致。有时,如果值为 0,则包含某些键,有时则省略这些键。我还没有找到可行的解决方案。
理想情况下,我想要一个可以通过函数使用的解决方案,因为我不想通过为每个项目引发异常来填充我的代码,但我不确定这是否可能。
这是我的代码。
using (StreamReader r = new StreamReader(@"path\file.JSON"))
{
string json = r.ReadToEnd();
var root = JsonConvert.DeserializeObject<Root>(json);
}
foreach (var i in root.value)
{
Dictionary<string, Dictionary<string, double>> HOLDING_DICT =
new Dictionary<string, Dictionary<string, double>>();
if (i.type == "1")
{
Dictionary<string, double> income_statement_dict = GET_DATA(i.data);
}
}static Dictionary<string, double> GET_DATA(DATA, data
{
Dictionary<string, double> temp_dict=
new Dictionary<string, double>();
temp_dict["itemx"] = data.thing.item;
return temp_dict;
}
它的 temp_dict["itemx"] = data.thing.item; 特别会抛出错误,我没有包括所有项目,但数量很大。
【问题讨论】:
-
问:你有没有考虑过使用Dictionary.TryGetValue()?
标签: c#