DynamicJson icon indicating copy to clipboard operation
DynamicJson copied to clipboard

I found a problem and solved him, about converting to a nullable type

Open loveyeguo opened this issue 7 years ago • 0 comments

In the method "DeserializeValue", once the nullable type is encountered. For example "datetime?", the conversion will fail. Need to add a method

public static class ConvertHelper
    {
        #region = ChangeType =
        public static object ChangeType(object obj, Type conversionType)
        {
            return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);
        }

        public static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {
            #region Nullable
            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nullableType, provider);
            }
            #endregion
            if (typeof(System.Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }
            return Convert.ChangeType(obj, conversionType, provider);
        }
        #endregion
    }

Then modify the method "DeserializeValue" to:


      private dynamic DeserializeValue(XElement element, Type elementType)
        {
            var value = ToValue(element);
            if (value is DynamicJson)
            {
                value = ((DynamicJson)value).Deserialize(elementType);
            }
            return ConvertHelper.ChangeType(value, elementType);
        }

Problem solved perfectly!

loveyeguo avatar Sep 19 '18 03:09 loveyeguo