public static bool TrySet(this JsonObject obj, string name, object value) { Debug.Assert(obj != null, "obj should probably not be null!"); Debug.Assert(!string.IsNullOrEmpty(name), "name cannot be null or empty."); if (obj == null) { return(false); } if (value == null) { obj.Set(name, JsonExtensions.Null()); } else { // If the type is nullable, strip off the Nullable<> which will // allow the comparisons below to convert correctly (since // we've already checked the value isn't null) Type memberType = value.GetType(); memberType = Nullable.GetUnderlyingType(memberType) ?? memberType; RuntimeTypeHandle handle = memberType.TypeHandle; // Set the value based on the type for known primitives if (handle.Equals(typeof(bool).TypeHandle)) { obj.Set(name, Convert.ToBoolean(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(int).TypeHandle) || handle.Equals(typeof(uint).TypeHandle) || handle.Equals(typeof(sbyte).TypeHandle) || handle.Equals(typeof(byte).TypeHandle) || handle.Equals(typeof(short).TypeHandle) || handle.Equals(typeof(ushort).TypeHandle) || handle.Equals(typeof(double).TypeHandle) || handle.Equals(typeof(float).TypeHandle) || handle.Equals(typeof(Decimal).TypeHandle) || handle.Equals(typeof(uint).TypeHandle)) { // Convert all numeric types into doubles obj.Set(name, Convert.ToDouble(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(long).TypeHandle) || handle.Equals(typeof(ulong).TypeHandle)) { if (!NumericCanRoundtrip(value, memberType)) { throw new ArgumentOutOfRangeException( name, value, string.Format( CultureInfo.InvariantCulture, Resources.JsonExtensions_TrySetValue_CannotRoundtripNumericValue, value, name)); } obj.Set(name, Convert.ToDouble(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(char).TypeHandle)) { // Convert characters to strings obj.Set(name, value.ToString()); } else if (handle.Equals(typeof(string).TypeHandle)) { obj.Set(name, value as string); } else if (handle.Equals(typeof(DateTime).TypeHandle)) { // Serialize DateTime as an ISO 8061 date/time obj.Set(name, ((DateTime)value).ToRoundtripDateString()); } else if (handle.Equals(typeof(DateTimeOffset).TypeHandle)) { // Serialize DateTimeOffset as an ISO 8061 date/time obj.Set(name, ((DateTimeOffset)value).DateTime.ToRoundtripDateString()); } else { return(false); } } return(true); }