Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if json array exists c#

Tags:

c#

json.net

I have a json object like so:

{
    "Name": "Mike",
    "Personaldetails": [
        {
            "Age": 25,
            "Surname": "Barnes"
        }
    ],
    "Address": [
        null
    ]
}

Now I have written C# to access this code and iterate over each object in the "Personal Details" array and into "Address" array.

How would I write a check to see if the array is null?

dynamic jsonObject = JsonConvert.DeserializeObject(data);

foreach (var obj in jsonObject.Personaldetails)
{
     if (obj.Age = 24)
     {
          //do stuff
     }
}

//This is where I am stuck
if(jsonObject.Address = null)
{
    return "null array";
}
//If another json stream was not null at "Address" array
else
{
    foreach (var obj in jsonObject.Address)
    {
         if (obj.arrayItem == "Something")
         {
              //do stuff
         }
    }
}
like image 629
Mike Barnes Avatar asked Feb 15 '23 13:02

Mike Barnes


2 Answers

Right as no one else seems to be paying attention, here is the answer...

The problem is with this bit of code:

"Address": [
    null
]

You are trying to check if Address is null, however this JSON does not represent a null Address. It shows a valid array, with one single null object. If this is correct, then you may want to try this:

if(jsonObject.Address == null || (jsonObject.Address[0] == null))
{
    return "null array";
}

Firstly, notice the use of == to check equality (rather than = for assignment).

Secondly, this will check if Address is null OR if the first object of the array is null, which I assume is what you are trying to do. It may also be worth adding in a length check to see if the array is just a single null element - but that depends on your requirements

like image 134
musefan Avatar answered Feb 23 '23 07:02

musefan


Your missing the double "==" to check for comparison, "=" is an assignment operation.

if(jsonObject.Address == null)
{
    return "null array";
}

Your JSON should look like this. Otherwise your not checking for a null array but instead an array with a null value for the first element of the array.

{
    "Name": "Mike",
    "Personaldetails": [
        {
            "Age": 25,
            "Surname": "Barnes"
        }
    ],
    "Address":  null
}

Then the code would be the following:

if(jsonObject.Address == null)
{
    return "null array";
}

If you need to keep the original JSON you can always do a check like so:

if(jsonObject.Address.Length > 0 && jsonObject.Address[0] == null)
{
    return "null array";
}
like image 27
Rob Carroll Avatar answered Feb 23 '23 09:02

Rob Carroll