using System; using ICD.Common.Properties; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ICD.Common.Utils.Extensions { /// /// Extension methods for working with JSON. /// public static class JsonExtensions { /// /// Writes the object value. /// /// /// /// /// [PublicAPI] public static void WriteObject(this JsonWriter extends, object value, JsonSerializer serializer, JsonConverter converter) { if (extends == null) throw new ArgumentNullException("extends"); if (serializer == null) throw new ArgumentNullException("serializer"); if (converter == null) throw new ArgumentNullException("converter"); JObject jObject = JObject.FromObject(value, serializer); jObject.WriteTo(extends, converter); } /// /// Gets the current value as an integer. /// /// /// [PublicAPI] public static int GetValueAsInt(this JsonReader extends) { if (extends == null) throw new ArgumentNullException("extends"); if (extends.TokenType == JsonToken.Integer) return (int)(long)extends.Value; string message = string.Format("Token {0} {1} is not {2}", extends.TokenType, extends.Value, JsonToken.Integer); throw new InvalidCastException(message); } /// /// Gets the current value as a string. /// /// /// [PublicAPI] public static string GetValueAsString(this JsonReader extends) { if (extends == null) throw new ArgumentNullException("extends"); if (extends.TokenType == JsonToken.String || extends.TokenType == JsonToken.Null) return extends.Value as string; string message = string.Format("Token {0} {1} is not {2}", extends.TokenType, extends.Value, JsonToken.String); throw new InvalidCastException(message); } /// /// Gets the current value as a bool. /// /// /// [PublicAPI] public static bool GetValueAsBool(this JsonReader extends) { if (extends == null) throw new ArgumentNullException("extends"); if (extends.TokenType == JsonToken.Boolean) return (bool)extends.Value; string message = string.Format("Token {0} {1} is not {2}", extends.TokenType, extends.Value, JsonToken.Boolean); throw new InvalidCastException(message); } /// /// Gets the current value as an enum. /// /// /// [PublicAPI] public static T GetValueAsEnum(this JsonReader extends) { if (extends == null) throw new ArgumentNullException("extends"); if (extends.TokenType == JsonToken.String) return EnumUtils.Parse(extends.GetValueAsString(), true); return (T)(object)extends.GetValueAsInt(); } } }