Check if c # json array exists

I have a json object like:

{ "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 in the "Address" array.

How do I write a check to find out if an 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 } } } 
+4
source share
2 answers

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

The problem is this piece of code:

 "Address": [ null ] 

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

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

First, note the use of == to verify equality (not = for assignment).

Secondly, this will check if Address null OR if the first array object that I am assuming is what you are trying to do. It may also be useful to add a length check to see if the array is just one single element - but that depends on your requirements.

+7
source

Skipping the double "==" to check the comparison, "=" is the assignment operation.

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

Your JSON should look like this. Otherwise, you will not check 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 will look like this:

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

If you need to keep the original JSON, you can always do this:

 if(jsonObject.Address.Length > 0 && jsonObject.Address[0] == null) { return "null array"; } 
+1
source

Source: https://habr.com/ru/post/1497247/


All Articles