So when I have a JsonNode I can just ask if it's a JsonObject or a JsonArray and work with those. But when the node is an actual value, how do I know whether it's a string, number or boolean?
Of course I could just try and parse the value, but then a number transmitted in a string would become a number instead of a string which I'd like to avoid.
I'm using System.Text.Json with .NET 6.
From the source, it looks like a JsonValue just wraps a JsonElement. So you can do .GetValue<JsonElement>() (which passes this check), and then inspect its ValueKind property.
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 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