-1

I am getting this error:

System.NullReferenceException: 'Object reference not set to an instance of an object'

I know why I am getting it - I am parsing some JSON, and unfortunately it is not consistent in including keys. Sometimes certain keys are included if the value is 0 other times the keys are omitted. I have not found a solution that works yet.

Ideally, I would like a solution that can be used via a function as I don't want to fill my code up with raising exceptions for each item but I am not sure if that's possible.

This is my code:

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

This line

temp_dict["itemx"] = data.thing.item;

in particular throws the error and I haven't included all the items but it's a significant amount.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JPWilson
  • 691
  • 4
  • 14

1 Answers1

2

you can add a null check in your code.

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

But again I have one question, Why do you need a dictionary to store only one key-value pair?

I would suggest returning only the string or double from GET_DATA method and just adding a string or double to the HOLDING_DICT as a value, not the dictionary.

As mentioned in the comment by @Sir Gufo, you can also try data?.thing != null depending on the C# version. But that is just a way of writing the same thing differently.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197