Check if json array exists c#
c#, json.net
Solution
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
Problem
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 } } } ```