Balasubramani M
Balasubramani M

Reputation: 8348

Handle null Json Value in C#. How to handle it here?

I have gone through some of the post regarding this but couldn't get the solution. How to handle the null value here in the following code?

 foreach (KeyValuePair<string, object> obj in mainList[i])
 {
     PList[i].Add(obj.Value.ToString());
 }

I am getting null value (null reference exception) while trying to get object value in the list. I have tried something like this,

foreach (KeyValuePair<string, object> obj in mainList[i])
{
   try
   {
       var check = obj.Value.ToString();
       PList[i].Add(check);
   }
   catch(NullReferenceException)
   {
       var check = "Null";
       PList[i].Add(check);
   }
}

I can achieve my target using the second snippet (using try catch blocks) but it seems to be very slow. It takes almost 30 seconds to process this for loop. So is there any other way on how to handle this null Json value?

mainList = List<Dictionary<String,String>>.
PList = List<String>.

Upvotes: 0

Views: 1343

Answers (1)

Chris Shao
Chris Shao

Reputation: 8231

You can check if value is null before add it to list.

foreach (KeyValuePair<string, object> obj in mainList[i])
{
    PList[i].Add(obj.Value == null ? "Null" : obj.Value.ToString());
}

Upvotes: 2

Related Questions