Last active
August 17, 2016 14:30
-
-
Save AronDavis/8f976a1ba3854e3f8198ae05d88d16c1 to your computer and use it in GitHub Desktop.
Newtonsoft JToken Extensions for dealing with nulls with Value<T> where T is a struct.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Newtonsoft.Json.Linq; | |
public static class JTokenExtensions | |
{ | |
/// <summary> | |
/// Extension of JToken Value<T> method. Used to avoid null exceptions with value types when parsing JToken. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="token"></param> | |
/// <param name="key"></param> | |
/// <returns></returns> | |
public static T ValueOrDefault<T>(this JToken token, object key) where T : struct | |
{ | |
return ValueOrDefault<T>(token[key]); | |
} | |
/// <summary> | |
/// Extension of JToken Value<T> method. Used to avoid null exceptions with value types when parsing JToken. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="token"></param> | |
/// <returns></returns> | |
public static T ValueOrDefault<T>(this JToken token) where T : struct | |
{ | |
if (token == null) | |
return default(T); | |
return token.Type == JTokenType.Null ? default(T) : token.Value<T>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment