Skip to content

Instantly share code, notes, and snippets.

@AronDavis
Last active August 17, 2016 14:30
Show Gist options
  • Save AronDavis/8f976a1ba3854e3f8198ae05d88d16c1 to your computer and use it in GitHub Desktop.
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.
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