json.net handling tokens that don't exist
开发者_JS百科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.
token["disambiguated"] == null
to check that token exists
token["disambiguated"].HasValues
to check that token has values
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.
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.
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.
精彩评论