【问题标题】:how can I handle System.NullReferenceException?我该如何处理 System.NullReferenceException?
【发布时间】: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; 特别会抛出错误,我没有包括所有项目,但数量很大。

【问题讨论】:

标签: c#


【解决方案1】:

您可以在代码中添加空检查。

if(data != null)
{
    if(data.thing != null)
    {
        temp_dict["itemx"] = data.thing.item;
    }
}

【讨论】:

    猜你喜欢
    • 2013-04-25
    • 2021-03-03
    • 2011-11-02
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多