1

Given an empty array with literal null value:

"someArray": [
  null
]

How would you detect the array does not have any children using JSON.NET?

if (json["someArray"].HasValues)

if (json["someArray"].Any())

if (json["someArray"].Any(p => (string)p != "null"))

if (json["someArray"].Any(p => p.Value<string>() != "null"))

None of that worked. All of these allowed the runtime to enter the if block.

EDIT

Definition of "works" is if the if block is not executed when array contains "null" value and is executed if it contains any children.

if (json["someArray"].Any(p => (string)p != null))

fails with Can not convert Object to String if array has any children and "works" if it contains "null".

if (json["someArray"].Any(p => p.Value<string>() != null))

also fails with Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken. if array has any children and "works" if it contains "null".

Any(x => x.Type != JTokenType.Null)

is the only one I found to do exactly what is expected which is skip the if block containing only "null" value and execute if block containing children.

2
  • Surly the value is null rather than "null"? json["someArray"].All(x => x == null) to detect if all the values are null, negate it if you don't want to enter the block when only nulls are present ? But whether this means "it has children" may be another thing entirely. What does an array with children look like? Commented Jul 17, 2020 at 5:14
  • app.quicktype.io?share=X3RgD2p2ZdYlEk3KovKr Commented Jul 17, 2020 at 5:19

1 Answer 1

4

You can check the Type of the JToken. A null literal in JSON is represented by a JValue with a Type of JTokenType.Null.

obj["someArray"].Any(x => x.Type != JTokenType.Null)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.