The accepted answer only works for specific use cases, namely that the node in question is of type JsonValue.
I propose a better option is to first test for the basic kind of types there are in JSON.
someObject["SomeNode"] is JsonArray
someObject["SomeNode"] is JsonObject
someObject["SomeNode"] is JsonValue
if the object is of type JsonValue one can use tryGetvalue to directly test for the expected value type
someObject["SomeNode"].AsValue().TryGetValue<someType>(out someType result)
TryGetValue returns true if it the value was parseble as the requested type.
If the expected type is completely unknown or variable (ugh), you could use the
someObject["SomeNode"].GetValue<JsonElement>().ValueKind
trick. But that only works for distinquishing between int and string and the bool values. Trying this on an array will give an exception. Therefore you first have to test with the "is" style syntax above.
if(someValue is string)
..? – SuperimposedAn expression of type System.Text.Json.JsonNode? cannot be handled by a pattern of type 'string'
. Not what I expected and not sure what it means exactly, thought a type check would always be possible. Edit: Same for other primitive type checks. – MatiasJsonValue
just wraps aJsonElement
. So you might be able to do.GetValue<JsonElement>()
(which passes this check), and the inspect itsValueKind
property? – YolandaJsonNodeExtensions.GetValueKind(this JsonNode node, JsonSerializerOptions options = null)
from this comment by steveharter to JsonNode feedback #55827 seems to do what you need. (Be sure to click onclick for samples
to see the code.) – Amphibolous