Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out what type a JsonValue is in System.Text.Json

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.

like image 802
Squirrelkiller Avatar asked Nov 22 '25 20:11

Squirrelkiller


2 Answers

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.

like image 61
canton7 Avatar answered Nov 24 '25 10:11

canton7


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.

like image 37
zu1b Avatar answered Nov 24 '25 09:11

zu1b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!