1

I have a small project where i recieve Json data from stream analytics and want to process it with a couple of functions to insert it into a relational database.

I've been debugging for a while and when I try to run a foreach loop to loop through the json data I sometimes recieve a Object reference not set to an instance of an object. error.

The error seems to be thrown every time I receive data, the loop will work on the data and the data will show up in the database but the error just bothers me.

So I started looking around on Stackoverflow and other forums for people that ran into a similar situation but couldn't find anything that could give me a little push into the right direction.

For testing I just log a string Data and the error still gets thrown.

The content class used is : HttpRequestMessage req

if (connection != null && connection.State == ConnectionState.Open)
{
    string content = await req.Content.ReadAsStringAsync();
    dynamic result = JsonConvert.DeserializeObject(content);
    log.LogInformation("Content recieved and deserialized.");

    foreach (var data in result)
    {
        log.LogInformation("Data");
    }
}

Can someone explain why this error occurs? I can't figure it out by debugging

Collin
  • 1,063
  • 1
  • 9
  • 28
  • `if (result != null) foreach...` – Miamy Mar 17 '20 at 10:31
  • What kind of `Class` content is ? Define that explicitly – Md Farid Uddin Kiron Mar 17 '20 at 10:31
  • @MdFaridUddinKiron The Class content is a HttpRequestMessage – Collin Mar 17 '20 at 10:35
  • 1) Check the **stack trace** of the exception to find out **where** it was raised (and with that **what** was `null`). 2) Find out _why_ it was `null`. ...all that is explained in the linked canonical answer. I don't know why someone voted to reopen the question, as long as you did not take at least these two steps. – René Vogt Mar 17 '20 at 10:38
  • Can you please copy the JSON content? JsonConvert.DeserializeObject() returns a JObject and supports IEnumerable, and it is obvious here that one of the elements being returned during this iteration causes an internal exception to occur. – Oguz Ozgul Mar 17 '20 at 10:45

0 Answers0