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
}
}
}
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
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With