Json.net processes tokens that do not exist

What is the best way to determine if a token exists? I use a crude way to just catch an error if this happens, but there must be a way to determine if it exists:

try { Response.Write(token["key"]); } catch { } 

I tried something like this:

 if (token["disambiguated"].FirstOrDefault().HasValues) 

but it does not work.

Thanks Steve.

+4
source share
3 answers
 token["disambiguated"] == null 

to check for a token

 token["disambiguated"].HasValues 

to verify that the token matters

+7
source

How do you fill in the token? If token is an instance (not null), then token["key"] should just return null, and not throw an exception. Obviously this would have to throw a null exception if the token is null, so all you have to do is make sure that token not null. I just tested this on the latest version of json.net.

0
source

I am not intimate with JSON.NET for JSON deserialization, but if you use C # 4, you can get a fairly simple solution using dynamic code.

I posted the code here that will allow you to write the code above:

 if (token.key!=null) Response.Write(token.key); 

If you use JSON.NET to deserialize JSON, then this might be a simpler solution for you.

-1
source

All Articles