4

What is the best way to detect if a token exists? I am using the crude way of simply catching the error if it happens but there must be a way to detect if it exists:

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

I have tried something like this:

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

but that does not seem to work.

Thanks, Steve.

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
stig
  • 41
  • 1
  • 2

4 Answers4

7
token["disambiguated"] == null

to check that token exists

token["disambiguated"].HasValues

to check that token has values

Genius
  • 1,784
  • 14
  • 12
0

How are you populating the token? If token is an instantiated (not null) value, then token["key"] should simply return null, not throw an exception. It obviously would throw a null exception if token is null so all you should need to do is make sure token is not null. I just tested this on the latest version of json.net.

bkaid
  • 51,465
  • 22
  • 112
  • 128
0

One thing you can do is create a method you can pass the token into that will validate whether to object/property/element exists. You will need to have the NuGet package Newtonsoft.Json.Linq to perform this action.

Method:

    public static bool TokenIsNullOrEmpty(JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }

Then you can use a conditional to provide a value whether an element/object/property exists:

var variable = TokenIsNullOrEmpty(obj["object/element/property name"]) == false ? obj["object/element/property name"].ToString() : "";

Hope this was helpful. Regards.

-1

I'm not intimate with JSON.NET for deserialising JSON, but if you're using C# 4 then you can get quite a simple solution via dynamic code.

I posted some code here that would allow you to write the code above like this:

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

If you're only using JSON.NET for deserialising JSON then this may be a simpler solution for you.

Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742