Пример #1
0
        public virtual void Write(Enum value)
        {
            string jsonName = null;
            Type   enumType = value.GetType();

            if (enumType.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(enumType, value))
            {
                Enum[]   flagList = GetFlagList(enumType, value);
                string[] strArray = new string[flagList.Length];
                for (int i = 0; i < flagList.Length; i++)
                {
                    strArray[i] = JsonNameAttribute.GetJsonName(flagList[i]);
                    if (string.IsNullOrEmpty(strArray[i]))
                    {
                        strArray[i] = flagList[i].ToString("f");
                    }
                }
                jsonName = string.Join(", ", strArray);
            }
            else
            {
                jsonName = JsonNameAttribute.GetJsonName(value);
                if (string.IsNullOrEmpty(jsonName))
                {
                    jsonName = value.ToString("f");
                }
            }
            this.Write(jsonName);
        }
Пример #2
0
        public virtual void Write(Enum value)
        {
            Type   type = value.GetType();
            string value2;

            if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value))
            {
                Enum[]   flagList = JsonWriter.GetFlagList(type, value);
                string[] array    = new string[flagList.Length];
                for (int i = 0; i < flagList.Length; i++)
                {
                    array[i] = JsonNameAttribute.GetJsonName(flagList[i]);
                    if (string.IsNullOrEmpty(array[i]))
                    {
                        array[i] = flagList[i].ToString("f");
                    }
                }
                value2 = string.Join(", ", array);
            }
            else
            {
                value2 = JsonNameAttribute.GetJsonName(value);
                if (string.IsNullOrEmpty(value2))
                {
                    value2 = value.ToString("f");
                }
            }
            this.Write(value2);
        }
Пример #3
0
        public virtual void Write(Enum value)
        {
            string text = null;
            Type   type = value.GetType();

            if (type.IsDefined(typeof(FlagsAttribute), inherit: true) && !Enum.IsDefined(type, value))
            {
                Enum[]   flagList = GetFlagList(type, value);
                string[] array    = new string[flagList.Length];
                for (int i = 0; i < flagList.Length; i++)
                {
                    array[i] = JsonNameAttribute.GetJsonName(flagList[i]);
                    if (string.IsNullOrEmpty(array[i]))
                    {
                        array[i] = flagList[i].ToString("f");
                    }
                }
                text = string.Join(", ", array);
            }
            else
            {
                text = JsonNameAttribute.GetJsonName(value);
                if (string.IsNullOrEmpty(text))
                {
                    text = value.ToString("f");
                }
            }
            Write(text);
        }
Пример #4
0
        public static string GetJsonName(object value)
        {
            if (value == null)
            {
                return(null);
            }
            Type       enumType = value.GetType();
            MemberInfo element  = null;

            if (enumType.IsEnum)
            {
                string name = Enum.GetName(enumType, value);
                if (string.IsNullOrEmpty(name))
                {
                    return(null);
                }
                element = enumType.GetField(name);
            }
            else
            {
                element = value as MemberInfo;
            }
            if (element == null)
            {
                throw new ArgumentException();
            }
            if (!Attribute.IsDefined(element, typeof(JsonNameAttribute)))
            {
                return(null);
            }
            JsonNameAttribute customAttribute = (JsonNameAttribute)Attribute.GetCustomAttribute(element, typeof(JsonNameAttribute));

            return(customAttribute.Name);
        }
Пример #5
0
        internal Dictionary <string, MemberInfo> CreateFieldMemberMap(Type objectType)
        {
            if (this.MemberMapCache.ContainsKey(objectType))
            {
                return(this.MemberMapCache[objectType]);
            }
            Dictionary <string, MemberInfo> dictionary = new Dictionary <string, MemberInfo>();

            foreach (FieldInfo info2 in objectType.GetFields())
            {
                if (info2.IsPublic && !JsonIgnoreAttribute.IsJsonIgnore(info2))
                {
                    string str2 = JsonNameAttribute.GetJsonName(info2);
                    if (string.IsNullOrEmpty(str2))
                    {
                        dictionary[info2.Name] = info2;
                    }
                    else
                    {
                        dictionary[str2] = info2;
                    }
                }
            }
            this.MemberMapCache[objectType] = dictionary;
            return(dictionary);
        }
Пример #6
0
        public virtual void Write(Enum value)
        {
            string enumName = null;

            Type type = value.GetType();

            if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value))
            {
                Enum[]   flags     = JsonWriter.GetFlagList(type, value);
                string[] flagNames = new string[flags.Length];
                for (int i = 0; i < flags.Length; i++)
                {
                    flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]);
                    if (String.IsNullOrEmpty(flagNames[i]))
                    {
                        flagNames[i] = flags[i].ToString("f");
                    }
                }
                enumName = String.Join(", ", flagNames);
            }
            else
            {
                enumName = JsonNameAttribute.GetJsonName(value);
                if (String.IsNullOrEmpty(enumName))
                {
                    enumName = value.ToString("f");
                }
            }

            this.Write(enumName);
        }
Пример #7
0
        public static string GetJsonName(object value)
        {
            if (value == null)
            {
                return(null);
            }
            Type       type       = value.GetType();
            MemberInfo memberInfo = null;

            if (type.IsEnum)
            {
                string name = Enum.GetName(type, value);
                if (string.IsNullOrEmpty(name))
                {
                    return(null);
                }
                memberInfo = type.GetField(name);
            }
            else
            {
                memberInfo = value as MemberInfo;
            }
            if (memberInfo == null)
            {
                throw new ArgumentException();
            }
            if (!Attribute.IsDefined(memberInfo, typeof(JsonNameAttribute)))
            {
                return(null);
            }
            JsonNameAttribute jsonNameAttribute = (JsonNameAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(JsonNameAttribute));

            return(jsonNameAttribute.Name);
        }
        protected Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            if (this.MemberMapCache.ContainsKey(objectType))
            {
                return(this.MemberMapCache[objectType]);
            }
            Dictionary <string, MemberInfo> dictionary = new Dictionary <string, MemberInfo>();

            PropertyInfo[] properties = objectType.GetProperties();
            foreach (PropertyInfo propertyInfo in properties)
            {
                if (propertyInfo.CanRead && propertyInfo.CanWrite)
                {
                    if (!JsonIgnoreAttribute.IsJsonIgnore(propertyInfo))
                    {
                        string jsonName = JsonNameAttribute.GetJsonName(propertyInfo);
                        if (string.IsNullOrEmpty(jsonName))
                        {
                            dictionary[propertyInfo.Name] = propertyInfo;
                        }
                        else
                        {
                            dictionary[jsonName] = propertyInfo;
                        }
                    }
                }
            }
            FieldInfo[] fields = objectType.GetFields();
            foreach (FieldInfo fieldInfo in fields)
            {
                if (fieldInfo.IsPublic)
                {
                    if (!JsonIgnoreAttribute.IsJsonIgnore(fieldInfo))
                    {
                        string jsonName2 = JsonNameAttribute.GetJsonName(fieldInfo);
                        if (string.IsNullOrEmpty(jsonName2))
                        {
                            dictionary[fieldInfo.Name] = fieldInfo;
                        }
                        else
                        {
                            dictionary[jsonName2] = fieldInfo;
                        }
                    }
                }
            }
            this.MemberMapCache[objectType] = dictionary;
            return(dictionary);
        }
Пример #9
0
        private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            if (this.MemberMapCache.ContainsKey(objectType))
            {
                return(this.MemberMapCache[objectType]);
            }
            Dictionary <string, MemberInfo> dictionary = new Dictionary <string, MemberInfo>();

            foreach (PropertyInfo info in objectType.GetProperties())
            {
                if ((info.CanRead && info.CanWrite) && !JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (string.IsNullOrEmpty(jsonName))
                    {
                        dictionary[info.Name] = info;
                    }
                    else
                    {
                        dictionary[jsonName] = info;
                    }
                }
            }
            foreach (FieldInfo info2 in objectType.GetFields())
            {
                if (info2.IsPublic && !JsonIgnoreAttribute.IsJsonIgnore(info2))
                {
                    string str2 = JsonNameAttribute.GetJsonName(info2);
                    if (string.IsNullOrEmpty(str2))
                    {
                        dictionary[info2.Name] = info2;
                    }
                    else
                    {
                        dictionary[str2] = info2;
                    }
                }
            }
            this.MemberMapCache[objectType] = dictionary;
            return(dictionary);
        }
Пример #10
0
        /// <summary>
        /// Gets the name specified for use in Json serialization.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetJsonName(object value)
        {
            if (value == null)
            {
                return(null);
            }

            Type       type       = value.GetType();
            MemberInfo memberInfo = null;

            if (TCU.GetTypeInfo(type).IsEnum)
            {
                string name = Enum.GetName(type, value);
                if (String.IsNullOrEmpty(name))
                {
                    return(null);
                }
                memberInfo = TCU.GetTypeInfo(type).GetField(name);
            }
            else
            {
                memberInfo = value as MemberInfo;
            }

            if (MemberInfo.Equals(memberInfo, null))
            {
                throw new ArgumentException();
            }

#if WINDOWS_STORE
            JsonNameAttribute attribute = memberInfo.GetCustomAttribute <JsonNameAttribute> (true);
#else
            JsonNameAttribute attribute = Attribute.GetCustomAttribute(memberInfo, typeof(JsonNameAttribute)) as JsonNameAttribute;
#endif
            return(attribute != null ? attribute.Name : null);
        }
Пример #11
0
        internal object CoerceType(Type targetType, object value)
        {
            bool flag = IsNullable(targetType);

            if (value == null)
            {
                if ((!this.allowNullValueTypes && targetType.IsValueType) && !flag)
                {
                    throw new JsonTypeCoercionException(string.Format("{0} does not accept null as a value", targetType.FullName));
                }
                return(value);
            }
            if (flag)
            {
                Type[] genericArguments = targetType.GetGenericArguments();
                if (genericArguments.Length == 1)
                {
                    targetType = genericArguments[0];
                }
            }
            Type c = value.GetType();

            if (targetType.IsAssignableFrom(c))
            {
                return(value);
            }
            if (!targetType.IsEnum)
            {
                object obj2;
                if (value is IDictionary)
                {
                    Dictionary <string, MemberInfo> dictionary;
                    return(this.CoerceType(targetType, (IDictionary)value, out dictionary));
                }
                if (typeof(IEnumerable).IsAssignableFrom(targetType) && typeof(IEnumerable).IsAssignableFrom(c))
                {
                    return(this.CoerceList(targetType, c, (IEnumerable)value));
                }
                if (value is string)
                {
                    if (targetType != typeof(DateTime))
                    {
                        if (targetType == typeof(Guid))
                        {
                            return(new Guid((string)value));
                        }
                        if (targetType != typeof(char))
                        {
                            if (targetType != typeof(Uri))
                            {
                                if (targetType == typeof(Version))
                                {
                                    return(new Version((string)value));
                                }
                            }
                            else
                            {
                                Uri uri;
                                if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                                {
                                    return(uri);
                                }
                            }
                        }
                        else if (((string)value).Length == 1)
                        {
                            return(((string)value)[0]);
                        }
                    }
                    else
                    {
                        DateTime time;
                        if (DateTime.TryParse((string)value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.RoundtripKind | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces, out time))
                        {
                            return(time);
                        }
                    }
                }
                else if (targetType == typeof(TimeSpan))
                {
                    return(new TimeSpan((long)this.CoerceType(typeof(long), value)));
                }
                TypeConverter converter = TypeDescriptor.GetConverter(targetType);
                if (converter.CanConvertFrom(c))
                {
                    return(converter.ConvertFrom(value));
                }
                converter = TypeDescriptor.GetConverter(c);
                if (converter.CanConvertTo(targetType))
                {
                    return(converter.ConvertTo(value, targetType));
                }
                try
                {
                    obj2 = Convert.ChangeType(value, targetType);
                }
                catch (Exception exception)
                {
                    throw new JsonTypeCoercionException(string.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), exception);
                }
                return(obj2);
            }
            if (!(value is string))
            {
                value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                return(Enum.ToObject(targetType, value));
            }
            if (!Enum.IsDefined(targetType, value))
            {
                foreach (FieldInfo info in targetType.GetFields())
                {
                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (((string)value).Equals(jsonName))
                    {
                        value = info.Name;
                        break;
                    }
                }
            }
            return(Enum.Parse(targetType, (string)value));
        }
Пример #12
0
        protected virtual void WriteObject(object value)
        {
            bool appendDelim = false;

            this.writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            try
            {
                Type objType = value.GetType();

                if (!String.IsNullOrEmpty(this.TypeHintName))
                {
                    if (appendDelim)
                    {
                        this.writer.Write(JsonReader.OperatorValueDelim);
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteLine();
                    this.Write(this.TypeHintName);
                    this.writer.Write(JsonReader.OperatorNameDelim);
                    this.Write(objType.FullName, true);
                }

                // serialize public properties
                PropertyInfo[] properties = objType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (!property.CanWrite || !property.CanRead)
                    {
                        continue;
                    }

                    if (this.IsIgnored(objType, property, value))
                    {
                        continue;
                    }

                    object propertyValue = property.GetValue(value, null);

                    if ((propertyValue == null) && SkipNullValue)
                    {
                        continue;
                    }

                    if (this.IsDefaultValue(property, propertyValue))
                    {
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.writer.Write(JsonReader.OperatorValueDelim);
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    string propertyName = JsonNameAttribute.GetJsonName(property);
                    if (String.IsNullOrEmpty(propertyName))
                    {
                        propertyName = property.Name;
                    }

                    this.WriteLine();
                    this.Write(propertyName);
                    this.writer.Write(JsonReader.OperatorNameDelim);
                    this.Write(propertyValue, true);
                }

                // serialize public fields
                FieldInfo[] fields = objType.GetFields();
                foreach (FieldInfo field in fields)
                {
                    if (!field.IsPublic || field.IsStatic)
                    {
                        continue;
                    }

                    if (this.IsIgnored(objType, field, value))
                    {
                        continue;
                    }

                    object fieldValue = field.GetValue(value);

                    if (this.IsDefaultValue(field, fieldValue))
                    {
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.writer.Write(JsonReader.OperatorValueDelim);
                        this.WriteLine();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    string fieldName = JsonNameAttribute.GetJsonName(field);
                    if (String.IsNullOrEmpty(fieldName))
                    {
                        fieldName = field.Name;
                    }

                    // use Attributes here to control naming
                    this.Write(fieldName);
                    this.writer.Write(JsonReader.OperatorNameDelim);
                    this.Write(fieldValue, true);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.writer.Write(JsonReader.OperatorObjectEnd);
        }
Пример #13
0
        internal object CoerceType(Type targetType, object value)
        {
            bool isNullable = TypeCoercionUtility.IsNullable(targetType);

            if (value == null)
            {
                if (!allowNullValueTypes &&
                    targetType.IsValueType &&
                    !isNullable)
                {
                    throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, targetType.FullName));
                }
                return(value);
            }

            if (isNullable)
            {
                // nullable types have a real underlying struct
                Type[] genericArgs = targetType.GetGenericArguments();
                if (genericArgs.Length == 1)
                {
                    targetType = genericArgs[0];
                }
            }

            Type actualType = value.GetType();

            if (targetType.IsAssignableFrom(actualType))
            {
                return(value);
            }

            if (targetType.IsEnum)
            {
                if (value is String)
                {
                    // AKS: Try to parse enum's for upper-case too, since we always serialize as lower-case
                    if (Enum.IsDefined(targetType, value))
                    {
                        return(Enum.Parse(targetType, (string)value));
                    }
                    if (Enum.IsDefined(targetType, ((string)value).ToUpper()))
                    {
                        return(Enum.Parse(targetType, ((string)value).ToUpper()));
                    }
                    // if isn't a defined value perhaps it is the JsonName
                    foreach (FieldInfo field in targetType.GetFields())
                    {
                        string jsonName = JsonNameAttribute.GetJsonName(field);
                        if (((string)value).Equals(jsonName))
                        {
                            value = field.Name;
                            break;
                        }
                    }
                    return(Enum.Parse(targetType, (string)value));
                }
                else
                {
                    value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                    return(Enum.ToObject(targetType, value));
                }
            }

//			if (targetType.IsPrimitive == false && targetType != typeof(string))
//			{
//				ConstructorInfo jsonConstructor = targetType.GetConstructors().FirstOrDefault(x => Attribute.IsDefined(x, typeof(JsonConstructor), true));
//				if (jsonConstructor != null && jsonConstructor.GetParameters().Count() == 1)
//				{
//					Console.Write("JsonConstructor! " + targetType.Name);
//					Type constructorArgType = jsonConstructor.GetParameters()[0].ParameterType;
//					return jsonConstructor.Invoke(new object[] { CoerceType(constructorArgType, value) });
//				}
//
//				MethodInfo jsonFactory = targetType.GetMethods().FirstOrDefault(x => Attribute.IsDefined(x, typeof(JsonFactoryMethod), true));
//				if (jsonFactory != null && jsonFactory.GetParameters().Count() == 1)
//				{
//					Console.Write("JsonFactory! " + targetType.Name);
//					Type factoryArgType = jsonFactory.GetParameters()[0].ParameterType;
//					return jsonFactory.Invoke(null, new object[] { CoerceType(factoryArgType, value) });
//				}
//			}
            if (value is IDictionary)
            {
                Dictionary <string, MemberInfo> memberMap;
                return(this.CoerceType(targetType, (IDictionary)value, out memberMap));
            }

            if (typeof(IEnumerable).IsAssignableFrom(targetType) &&
                typeof(IEnumerable).IsAssignableFrom(actualType))
            {
                return(this.CoerceList(targetType, actualType, (IEnumerable)value));
            }

            if (value is String)
            {
                if (targetType == typeof(DateTime))
                {
                    DateTime date;
                    if (DateTime.TryParse(
                            (string)value,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                            out date))
                    {
                        return(date);
                    }
                }
                else
                if (targetType == typeof(Guid))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Guid((string)value));
                }
                else
                if (targetType == typeof(Char))
                {
                    if (((string)value).Length == 1)
                    {
                        return(((string)value) [0]);
                    }
                }
                else
                if (targetType == typeof(Uri))
                {
                    Uri uri;
                    if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                    {
                        return(uri);
                    }
                }
                else
                if (targetType == typeof(Version))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Version((string)value));
                }
            }
            else
            if (targetType == typeof(TimeSpan))
            {
                return(new TimeSpan((long)this.CoerceType(typeof(Int64), value)));
            }

            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter.CanConvertFrom(actualType))
            {
                return(converter.ConvertFrom(value));
            }

            converter = TypeDescriptor.GetConverter(actualType);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }

            try
            {
                // fall back to basics
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception ex)
            {
                throw new JsonTypeCoercionException(
                          String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex);
            }
        }
Пример #14
0
        internal object CoerceType(Type targetType, object value)
        {
            bool isNullable = TypeCoercionUtility.IsNullable(targetType);

            if (value == null)
            {
                if (!allowNullValueTypes &&
                    targetType.IsValueType &&
                    !isNullable)
                {
                    throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, targetType.FullName));
                }
                return(value);
            }

            if (isNullable)
            {
                // nullable types have a real underlying struct
                Type[] genericArgs = targetType.GetGenericArguments();
                if (genericArgs.Length == 1)
                {
                    targetType = genericArgs[0];
                }
            }

            Type actualType = value.GetType();

            if (targetType.IsAssignableFrom(actualType))
            {
                return(value);
            }

            if (targetType.IsEnum)
            {
                if (value is String)
                {
                    if (!Enum.IsDefined(targetType, value))
                    {
                        // if isn't a defined value perhaps it is the JsonName
                        foreach (FieldInfo field in targetType.GetFields())
                        {
                            string jsonName = JsonNameAttribute.GetJsonName(field);
                            if (((string)value).Equals(jsonName))
                            {
                                value = field.Name;
                                break;
                            }
                        }
                    }
                    //Julien: Added check for enums (previously didn't have try catch and wasn't case-insensitive)
                    //we don't want JSONFx to entirely abandon the parsing just because the user badly entered an enum
                    //instead just return null
                    object output;
                    try
                    {
                        output = Enum.Parse(targetType, (string)value, true);
                    }
                    catch (ArgumentException)
                    {
                        //If value is 'null', handle that gracefully.  Can happen when enum is stored as string on other end, e.g. w/ DBs
                        if (((string)value).ToLower() != "null")
                        {
                            UnityEngine.Debug.LogWarning("JSONFx could not parse '" + (string)value + "' as a(n) " + targetType.ToString());
                        }

                        //output = Activator.CreateInstance(targetType); //if we want to return the default for this enum
                        output = null;
                    }
                    return(output);
                }
                else
                {
                    value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                    return(Enum.ToObject(targetType, value));
                }
            }

            if (value is IDictionary)
            {
                Dictionary <string, MemberInfo> memberMap;
                return(this.CoerceType(targetType, (IDictionary)value, out memberMap));
            }

            if (typeof(IEnumerable).IsAssignableFrom(targetType) &&
                typeof(IEnumerable).IsAssignableFrom(actualType))
            {
                return(this.CoerceList(targetType, actualType, (IEnumerable)value));
            }

            if (value is String)
            {
                if (targetType == typeof(DateTime))
                {
                    DateTime date;
                    if (DateTime.TryParse(
                            (string)value,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                            out date))
                    {
                        return(date);
                    }
                }
                else if (targetType == typeof(Guid))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Guid((string)value));
                }
                else if (targetType == typeof(Char))
                {
                    if (((string)value).Length == 1)
                    {
                        return(((string)value)[0]);
                    }
                }
                else if (targetType == typeof(Uri))
                {
                    Uri uri;
                    if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                    {
                        return(uri);
                    }
                }
                else if (targetType == typeof(Version))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Version((string)value));
                }
            }
            else if (targetType == typeof(TimeSpan))
            {
                return(new TimeSpan((long)this.CoerceType(typeof(Int64), value)));
            }
            //Julien: Added to be able to deserialize times in epoch format
            //Commented because of inconsistencies: Java uses milliseconds & .NET uses ticks
            //else if (targetType == typeof(DateTime) && value is Decimal)
            //{
            //    return new DateTime((long)this.CoerceType(typeof(Int64), value));
            //}

            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter.CanConvertFrom(actualType))
            {
                return(converter.ConvertFrom(value));
            }

            converter = TypeDescriptor.GetConverter(actualType);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }

            try
            {
                // fall back to basics
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception ex)
            {
                throw new JsonTypeCoercionException(
                          String.Format("Error converting {0} to {1} for value: " + value.ToString(), value.GetType().FullName, targetType.FullName), ex);
            }
        }
Пример #15
0
        protected virtual void WriteObject(object value, Type type)
        {
            bool flag = false;

            Writer.Write('{');
            depth++;
            if (depth > settings.MaxDepth)
            {
                throw new JsonSerializationException($"The maxiumum depth of {settings.MaxDepth} was exceeded. Check for cycles in object graph.");
            }
            try
            {
                if (!string.IsNullOrEmpty(settings.TypeHintName))
                {
                    if (flag)
                    {
                        WriteObjectPropertyDelim();
                    }
                    else
                    {
                        flag = true;
                    }
                    WriteObjectProperty(settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name);
                }
                bool           flag2      = type.IsGenericType && type.Name.StartsWith("<>f__AnonymousType");
                PropertyInfo[] properties = type.GetProperties();
                PropertyInfo[] array      = properties;
                foreach (PropertyInfo propertyInfo in array)
                {
                    if (!propertyInfo.CanRead || (!propertyInfo.CanWrite && !flag2) || IsIgnored(type, propertyInfo, value))
                    {
                        continue;
                    }
                    object value2 = propertyInfo.GetValue(value, null);
                    if (!IsDefaultValue(propertyInfo, value2))
                    {
                        if (flag)
                        {
                            WriteObjectPropertyDelim();
                        }
                        else
                        {
                            flag = true;
                        }
                        string text = JsonNameAttribute.GetJsonName(propertyInfo);
                        if (string.IsNullOrEmpty(text))
                        {
                            text = propertyInfo.Name;
                        }
                        WriteObjectProperty(text, value2);
                    }
                }
                FieldInfo[] fields = type.GetFields();
                FieldInfo[] array2 = fields;
                foreach (FieldInfo fieldInfo in array2)
                {
                    if (!fieldInfo.IsPublic || fieldInfo.IsStatic || IsIgnored(type, fieldInfo, value))
                    {
                        continue;
                    }
                    object value3 = fieldInfo.GetValue(value);
                    if (!IsDefaultValue(fieldInfo, value3))
                    {
                        if (flag)
                        {
                            WriteObjectPropertyDelim();
                            WriteLine();
                        }
                        else
                        {
                            flag = true;
                        }
                        string text2 = JsonNameAttribute.GetJsonName(fieldInfo);
                        if (string.IsNullOrEmpty(text2))
                        {
                            text2 = fieldInfo.Name;
                        }
                        WriteObjectProperty(text2, value3);
                    }
                }
            }
            finally
            {
                depth--;
            }
            if (flag)
            {
                WriteLine();
            }
            Writer.Write('}');
        }
Пример #16
0
        private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            if (this.MemberMapCache.ContainsKey(objectType))
            {
                // map was stored in cache
                return(this.MemberMapCache[objectType]);
            }

            // create a new map
            Dictionary <string, MemberInfo> memberMap = new Dictionary <string, MemberInfo>();

            // load properties into property map
            //PropertyInfo[] properties = objectType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            IList <PropertyInfo> properties = GetAllProperties(objectType);

            foreach (PropertyInfo info in properties)
            {
                if (!info.CanRead || !info.CanWrite)
                {
                    continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    string name = NameResolver.CSharpToJson(info.Name);
                    memberMap[name] = info;
//					memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // load public fields into property map
//			FieldInfo[] fields = objectType.GetFields();
//			FieldInfo[] fields = objectType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public );
            IList <FieldInfo> fields = GetAllFields(objectType);

            foreach (FieldInfo info in fields)
            {
//				if (!info.IsPublic)
//				{
//					continue;
//				}

                if (info.IsPrivate)
                {
                    int breakhere = 0;
                    ++breakhere;
                    //continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    string name = NameResolver.CSharpToJson(info.Name);
                    memberMap[name] = info;
//					memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // store in cache for repeated usage
            this.MemberMapCache[objectType] = memberMap;

            return(memberMap);
        }
Пример #17
0
        /** Creates a member map for the type */
        private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            Dictionary <string, MemberInfo> memberMap;

            if (this.MemberMapCache.TryGetValue(objectType, out memberMap))
            {
                // map was stored in cache
                return(memberMap);
            }

            // create a new map
            memberMap = new Dictionary <string, MemberInfo>();

            // load properties into property map
            Type tp = objectType;

            while (tp != null)
            {
                PropertyInfo[] properties = TCU.GetTypeInfo(tp).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                for (int i = 0; i < properties.Length; i++)
                {
                    PropertyInfo info = properties [i];
                    if (!info.CanRead || !info.CanWrite)
                    {
                        continue;
                    }

                    if (JsonIgnoreAttribute.IsJsonIgnore(info))
                    {
                        continue;
                    }

                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (String.IsNullOrEmpty(jsonName))
                    {
                        memberMap[info.Name] = info;
                    }
                    else
                    {
                        memberMap[jsonName] = info;
                    }
                }

                // load public fields into property map
                FieldInfo[] fields = TCU.GetTypeInfo(tp).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                foreach (FieldInfo info in fields)
                {
                    if (!info.IsPublic &&
        #if WINDOWS_STORE
                        info.GetCustomAttribute <JsonMemberAttribute>(false) == null
        #else
                        info.GetCustomAttributes(typeof(JsonMemberAttribute), false).Length == 0
        #endif
                        )
                    {
                        continue;
                    }

                    if (JsonIgnoreAttribute.IsJsonIgnore(info))
                    {
                        continue;
                    }

                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (String.IsNullOrEmpty(jsonName))
                    {
                        memberMap[info.Name] = info;
                    }
                    else
                    {
                        memberMap[jsonName] = info;
                    }
                }

                tp = tp.BaseType;
            }

            // store in cache for repeated usage
            this.MemberMapCache[objectType] = memberMap;

            return(memberMap);
        }
Пример #18
0
        internal object CoerceType(Type targetType, object value)
        {
            bool isNullable = TypeCoercionUtility.IsNullable(targetType);

            if (value == null)
            {
                if (!allowNullValueTypes &&
                    TCU.GetTypeInfo(targetType).IsValueType&&
                    !isNullable)
                {
                    throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, new System.Object[] { targetType.FullName }));
                }
                return(value);
            }

            if (isNullable)
            {
                // nullable types have a real underlying struct
                Type[] genericArgs = targetType.GetGenericArguments();
                if (genericArgs.Length == 1)
                {
                    targetType = genericArgs[0];
                }
            }

            Type actualType = value.GetType();

            if (TCU.GetTypeInfo(targetType).IsAssignableFrom(TCU.GetTypeInfo(actualType)))
            {
                return(value);
            }

            if (TCU.GetTypeInfo(targetType).IsEnum)
            {
                if (value is String)
                {
                    if (!Enum.IsDefined(targetType, value))
                    {
                        // if isn't a defined value perhaps it is the JsonName
                        foreach (FieldInfo field in TCU.GetTypeInfo(targetType).GetFields())
                        {
                            string jsonName = JsonNameAttribute.GetJsonName(field);
                            if (((string)value).Equals(jsonName))
                            {
                                value = field.Name;
                                break;
                            }
                        }
                    }

                    return(Enum.Parse(targetType, (string)value));
                }
                else
                {
                    value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                    return(Enum.ToObject(targetType, value));
                }
            }

            if (value is IDictionary)
            {
                Dictionary <string, MemberInfo> memberMap;
                return(this.CoerceType(targetType, (IDictionary)value, out memberMap));
            }

            if (TCU.GetTypeInfo(typeof(IEnumerable)).IsAssignableFrom(TCU.GetTypeInfo(targetType)) &&
                TCU.GetTypeInfo(typeof(IEnumerable)).IsAssignableFrom(TCU.GetTypeInfo(actualType)))
            {
                return(this.CoerceList(targetType, actualType, (IEnumerable)value));
            }

            if (value is String)
            {
                if (Type.Equals(targetType, typeof(DateTime)))
                {
                    DateTime date;
                    if (DateTime.TryParse(
                            (string)value,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                            out date))
                    {
                        return(date);
                    }
                }
                else if (Type.Equals(targetType, typeof(Guid)))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Guid((string)value));
                }
                else if (Type.Equals(targetType, typeof(Char)))
                {
                    if (((string)value).Length == 1)
                    {
                        return(((string)value)[0]);
                    }
                }
                else if (Equals(targetType, typeof(Uri)))
                {
                    Uri uri;
                    if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                    {
                        return(uri);
                    }
                }
                else if (Type.Equals(targetType, typeof(Version)))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Version((string)value));
                }
            }
            else if (Type.Equals(targetType, typeof(TimeSpan)))
            {
                return(new TimeSpan((long)this.CoerceType(typeof(Int64), value)));
            }

#if !WINPHONE_8
            TypeConverter converter = TypeDescriptor.GetConverter(targetType);
            if (converter.CanConvertFrom(actualType))
            {
                return(converter.ConvertFrom(value));
            }

            converter = TypeDescriptor.GetConverter(actualType);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }
#endif

            try
            {
                // fall back to basics
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception ex)
            {
                throw new JsonTypeCoercionException(
                          String.Format("Error converting {0} to {1}", new System.Object[] { value.GetType().FullName, targetType.FullName }), ex);
            }
        }
Пример #19
0
		protected virtual void WriteObject(object value, Type type, bool serializePrivate)
		{
			bool appendDelim = false;

			if (settings.HandleCyclicReferences && !type.IsValueType)
			{
				int prevIndex = 0;
				if (this.previouslySerializedObjects.TryGetValue (value, out prevIndex)) {
					this.Writer.Write(JsonReader.OperatorObjectStart);
					this.WriteObjectProperty("@ref", prevIndex);
					this.WriteLine();
					this.Writer.Write(JsonReader.OperatorObjectEnd);
					return;
				} else {
					this.previouslySerializedObjects.Add (value, this.previouslySerializedObjects.Count);
				}
			}

			this.Writer.Write(JsonReader.OperatorObjectStart);

			this.depth++;
			if (this.depth > this.settings.MaxDepth)
			{
				throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
			}
			try
			{
				if (!String.IsNullOrEmpty(this.settings.TypeHintName))
				{
					if (appendDelim)
					{
						this.WriteObjectPropertyDelim();
					}
					else
					{
						appendDelim = true;
					}

					this.WriteObjectProperty(this.settings.TypeHintName, type.FullName+", "+type.Assembly.GetName().Name);
				}

				bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);

				// serialize public properties
				PropertyInfo[] properties = type.GetProperties();
				foreach (PropertyInfo property in properties)
				{
					if (!property.CanRead) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+property.Name+" : cannot read");
						continue;
					}
					
					if (!property.CanWrite && !anonymousType) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+property.Name+" : cannot write");
						continue;
					}
					
					if (this.IsIgnored(type, property, value)) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+property.Name+" : is ignored by settings");
						continue;
					}
					
					if (property.GetIndexParameters ().Length != 0) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+property.Name+" : is indexed");
						continue;
					}
					
					object propertyValue = property.GetValue(value, null);
					if (this.IsDefaultValue(property, propertyValue)) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+property.Name+" : is default value");
						continue;
					}
				
					if (appendDelim)
						this.WriteObjectPropertyDelim();
					else
						appendDelim = true;

					// use Attributes here to control naming
					string propertyName = JsonNameAttribute.GetJsonName(property);
					if (String.IsNullOrEmpty(propertyName))
						propertyName = property.Name;

					this.WriteObjectProperty(propertyName, propertyValue);
				}

				// serialize public fields
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo field in fields)
				{
					if (field.IsStatic || (!field.IsPublic && field.GetCustomAttributes(typeof(JsonMemberAttribute),true).Length == 0)) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+field.Name+" : not public or is static (and does not have a JsonMember attribute)");
						continue;
					}
					
					if (this.IsIgnored(type, field, value)) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+field.Name+" : ignored by settings");
						continue;
					}

					object fieldValue = field.GetValue(value);
					if (this.IsDefaultValue(field, fieldValue)) {
						if (Settings.DebugMode)
							Console.WriteLine ("Cannot serialize "+field.Name+" : is default value");
						continue;
					}

					if (appendDelim)
					{
						this.WriteObjectPropertyDelim();
						this.WriteLine();
					} else
					{
						appendDelim = true;
					}
					
					// use Attributes here to control naming
					string fieldName = JsonNameAttribute.GetJsonName(field);
					if (String.IsNullOrEmpty(fieldName))
						fieldName = field.Name;

					this.WriteObjectProperty(fieldName, fieldValue);
				}
			}
			finally
			{
				this.depth--;
			}

			if (appendDelim)
				this.WriteLine();
			
			this.Writer.Write(JsonReader.OperatorObjectEnd);
		}
Пример #20
0
        protected virtual void WriteObject(object value, Type type)
        {
            bool appendDelim = false;

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }
            try
            {
                if (!String.IsNullOrEmpty(this.settings.TypeHintName))
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(this.settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name);
                }

#if JSONFX_SERIALIZE_PROPERTIES
                bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);
                // serialize public properties
                IList <PropertyInfo> properties = TypeCoercionUtility.GetAllProperties(type);
//				PropertyInfo[] properties = type.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (!property.CanRead)
                    {
                        continue;
                    }

                    if (!property.CanWrite && !anonymousType)
                    {
                        continue;
                    }

                    if (this.IsIgnored(type, property, value))
                    {
                        continue;
                    }

                    if (property.PropertyType == typeof(Action))
                    {
                        continue;
                    }

                    object propertyValue = property.GetValue(value, null);
                    if (this.IsDefaultValue(property, propertyValue))
                    {
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    // use Attributes here to control naming
                    string propertyName = JsonNameAttribute.GetJsonName(property);
                    if (String.IsNullOrEmpty(propertyName))
                    {
                        propertyName = NameResolver.CSharpToJson(property.Name);
//						propertyName = property.Name;
                    }

                    this.WriteObjectProperty(propertyName, propertyValue);
                }
#endif

                // serialize public fields
                IList <FieldInfo> fields = TypeCoercionUtility.GetAllFields(type);
//				FieldInfo[] fields = type.GetFields();
                foreach (FieldInfo field in fields)
                {
//					if (!field.IsPublic || field.IsStatic)
//					{
//						continue;
//					}

                    if (field.IsPrivate)
                    {
                        int breakhere = 1;
                        ++breakhere;
                    }

                    if (/*field.IsPrivate ||*/ field.IsStatic)
                    {
                        continue;
                    }

                    if (this.IsIgnored(type, field, value))
                    {
                        continue;
                    }

                    if (field.FieldType == typeof(Action))
                    {
                        continue;
                    }

                    object fieldValue = field.GetValue(value);
                    if (this.IsDefaultValue(field, fieldValue))
                    {
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                        this.WriteLine();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    // use Attributes here to control naming
                    string fieldName = JsonNameAttribute.GetJsonName(field);
                    if (String.IsNullOrEmpty(fieldName))
                    {
                        fieldName = NameResolver.CSharpToJson(field.Name);
//						fieldName = field.Name;
                    }

                    this.WriteObjectProperty(fieldName, fieldValue);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Пример #21
0
        internal Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            if (this.MemberMapCache.ContainsKey(objectType))
            {
                // map was stored in cache
                return(this.MemberMapCache[objectType]);
            }

            // create a new map
            Dictionary <string, MemberInfo> memberMap = new Dictionary <string, MemberInfo>();

            // load properties into property map
            PropertyInfo[] properties = objectType.GetProperties();
            foreach (PropertyInfo info in properties)
            {
                if (!info.CanRead || !info.CanWrite)
                {
                    continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // load public fields into property map
            FieldInfo[] fields = objectType.GetFields();
            foreach (FieldInfo info in fields)
            {
                if (!info.IsPublic)
                {
                    continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // store in cache for repeated usage
            this.MemberMapCache[objectType] = memberMap;

            return(memberMap);
        }
Пример #22
0
        protected virtual void WriteObject(object value, Type type)
        {
            bool appendDelim = false;

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }
            try
            {
                if (!String.IsNullOrEmpty(this.settings.TypeHintName))
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(this.settings.TypeHintName,
                                             type.FullName + ", " + type.Assembly.GetName().Name);
                }

                bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);

                // serialize public properties
                PropertyInfo[] properties = type.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (!property.CanRead)
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + property.Name + " : cannot read");
                        }
                        continue;
                    }

                    if (!property.CanWrite && !anonymousType)
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + property.Name + " : cannot write");
                        }
                        continue;
                    }

                    if (this.IsIgnored(type, property, value))
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + property.Name + " : is ignored by settings");
                        }
                        continue;
                    }

                    if (property.GetIndexParameters().Length != 0)
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + property.Name + " : is indexed");
                        }
                        continue;
                    }

                    object propertyValue = property.GetValue(value, null);
                    if (this.IsDefaultValue(property, propertyValue))
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + property.Name + " : is default value");
                        }
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    // use Attributes here to control naming
                    string propertyName = JsonNameAttribute.GetJsonName(property);
                    if (String.IsNullOrEmpty(propertyName))
                    {
                        propertyName = property.Name;
                    }

                    this.WriteObjectProperty(propertyName, propertyValue);
                }

                // serialize public fields
                FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (FieldInfo field in fields)
                {
                    if (!Attribute.IsDefined(type, typeof(SerializeCompilerGenerated)) &&
                        Attribute.IsDefined(field, typeof(CompilerGeneratedAttribute)))
                    {
                        continue;
                    }

                    if (field.IsStatic)
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + field.Name + " : is static");
                        }
                        continue;
                    }

                    if (this.IsIgnored(type, field, value))
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + field.Name + " : ignored by settings");
                        }
                        continue;
                    }

                    object fieldValue = field.GetValue(value);
                    if (this.IsDefaultValue(field, fieldValue))
                    {
                        if (Settings.DebugMode)
                        {
                            Console.WriteLine("Cannot serialize " + field.Name + " : is default value");
                        }
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                        this.WriteLine();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    // use Attributes here to control naming
                    string fieldName = JsonNameAttribute.GetJsonName(field);
                    if (String.IsNullOrEmpty(fieldName))
                    {
                        fieldName = field.Name;
                    }

                    this.WriteObjectProperty(fieldName, fieldValue);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }

            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Пример #23
0
        public virtual object CoerceType(Type targetType, object value)
        {
            //Discarded unreachable code: IL_02be, IL_02e8
            bool flag = IsNullable(targetType);

            if (value == null)
            {
                if (!allowNullValueTypes && targetType.IsValueType && !flag)
                {
                    throw new JsonTypeCoercionException($"{targetType.FullName} does not accept null as a value");
                }
                return(value);
            }
            if (flag)
            {
                Type[] genericArguments = targetType.GetGenericArguments();
                if (genericArguments.Length == 1)
                {
                    targetType = genericArguments[0];
                }
            }
            Type type = value.GetType();

            if (targetType.IsAssignableFrom(type))
            {
                return(value);
            }
            if (targetType.IsEnum)
            {
                if (value is string)
                {
                    if (!Enum.IsDefined(targetType, value))
                    {
                        FieldInfo[] fields = targetType.GetFields();
                        foreach (FieldInfo fieldInfo in fields)
                        {
                            string jsonName = JsonNameAttribute.GetJsonName(fieldInfo);
                            if (((string)value).Equals(jsonName))
                            {
                                value = fieldInfo.Name;
                                break;
                            }
                        }
                    }
                    return(Enum.Parse(targetType, (string)value));
                }
                value = CoerceType(Enum.GetUnderlyingType(targetType), value);
                return(Enum.ToObject(targetType, value));
            }
            Dictionary <string, MemberInfo> memberMap;

            if (value is IDictionary)
            {
                return(CoerceType(targetType, (IDictionary)value, out memberMap));
            }
            if (typeof(IEnumerable).IsAssignableFrom(targetType) && typeof(IEnumerable).IsAssignableFrom(type))
            {
                return(CoerceList(targetType, type, (IEnumerable)value));
            }
            if (value is string)
            {
                if (targetType == typeof(DateTime))
                {
                    if (DateTime.TryParse((string)value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.RoundtripKind, out var result))
                    {
                        return(result);
                    }
                }
                else
                {
                    if (targetType == typeof(Guid))
                    {
                        return(new Guid((string)value));
                    }
                    if (targetType == typeof(char))
                    {
                        if (((string)value).Length == 1)
                        {
                            return(((string)value)[0]);
                        }
                    }
                    else if (targetType == typeof(Uri))
                    {
                        if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out var result2))
                        {
                            return(result2);
                        }
                    }
                    else if (targetType == typeof(Version))
                    {
                        return(new Version((string)value));
                    }
                }
            }
            else if (targetType == typeof(TimeSpan))
            {
                return(new TimeSpan((long)CoerceType(typeof(long), value)));
            }
            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter.CanConvertFrom(type))
            {
                return(converter.ConvertFrom(value));
            }
            converter = TypeDescriptor.GetConverter(type);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }
            try
            {
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception innerException)
            {
                throw new JsonTypeCoercionException($"Error converting {value.GetType().FullName} to {targetType.FullName}", innerException);
            }
        }
Пример #24
0
        protected virtual void WriteObject(object value, Type type)
        {
            bool appendDelim = false;

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }
            try
            {
                if (!String.IsNullOrEmpty(this.settings.TypeHintName))
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(this.settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name);
                }

                bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);

                if (this.settings.SerializeProperties)
                {
                    // serialize public properties
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo property in properties)
                    {
                        if (!property.CanRead)
                        {
                            continue;
                        }

                        if (!property.CanWrite && !anonymousType)
                        {
                            continue;
                        }

                        if (this.IsIgnored(type, property, value))
                        {
                            continue;
                        }

                        object propertyValue = property.GetValue(value, null);
                        if (this.IsDefaultValue(property, propertyValue))
                        {
                            continue;
                        }

                        if (appendDelim)
                        {
                            this.WriteObjectPropertyDelim();
                        }
                        else
                        {
                            appendDelim = true;
                        }

                        // use Attributes here to control naming
                        string propertyName = JsonNameAttribute.GetJsonName(property);
                        if (String.IsNullOrEmpty(propertyName))
                        {
                            propertyName = property.Name;
                        }

                        this.WriteObjectProperty(propertyName, propertyValue);
                    }
                }

                // serialize public fields
                FieldInfo[] fields = type.GetFields();
                foreach (FieldInfo field in fields)
                {
                    if (!field.IsPublic || field.IsStatic)
                    {
                        continue;
                    }

                    if (this.IsIgnored(type, field, value))
                    {
                        continue;
                    }

                    object fieldValue = field.GetValue(value);
                    if (this.IsDefaultValue(field, fieldValue))
                    {
                        continue;
                    }

                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                        this.WriteLine();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    // use Attributes here to control naming
                    string fieldName = JsonNameAttribute.GetJsonName(field);
                    if (String.IsNullOrEmpty(fieldName))
                    {
                        fieldName = field.Name;
                    }

                    this.WriteObjectProperty(fieldName, fieldValue);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Пример #25
0
        public void GetMemberWritingMap(Type objectType, JsonWriterSettings settings, out KeyValuePair <string, FieldInfo>[] outFields, out KeyValuePair <string, PropertyInfo>[] outProps)
        {
            if (writingMaps == null)
            {
                writingMaps = new Dictionary <Type, KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]> > ();
            }

            KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]> pair;

            if (writingMaps.TryGetValue(objectType, out pair))
            {
                outFields = pair.Key;
                outProps  = pair.Value;
                return;
            }

            bool anonymousType = objectType.IsGenericType && objectType.Name.StartsWith(JsonWriter.AnonymousTypePrefix);

            Type tp = objectType;

            if (fieldList == null)
            {
                fieldList = new List <KeyValuePair <string, FieldInfo> > ();
            }

            if (propList == null)
            {
                propList = new List <KeyValuePair <string, PropertyInfo> > ();
            }

            fieldList.Clear();
            propList.Clear();

            while (tp != null)
            {
                FieldInfo[] fields = tp.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                for (int j = 0; j < fields.Length; j++)
                {
                    FieldInfo field = fields[j];

                    if (field.IsStatic || (!field.IsPublic && field.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length == 0))
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize " + field.Name + " : not public or is static (and does not have a JsonMember attribute)");
                        continue;
                    }

                    if (settings.IsIgnored(objectType, field, null))
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize " + field.Name + " : ignored by settings");
                        continue;
                    }

                    // use Attributes here to control naming
                    string fieldName = JsonNameAttribute.GetJsonName(field);
                    if (String.IsNullOrEmpty(fieldName))
                    {
                        fieldName = field.Name;
                    }

                    fieldList.Add(new KeyValuePair <string, FieldInfo> (fieldName, field));
                }

                PropertyInfo[] properties = tp.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                for (int j = 0; j < properties.Length; j++)
                {
                    PropertyInfo property = properties[j];

                    //Console.WriteLine (property.Name);
                    if (!property.CanRead)
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize "+property.Name+" : cannot read");
                        continue;
                    }

                    if (!property.CanWrite && !anonymousType)
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize "+property.Name+" : cannot write");
                        continue;
                    }

                    if (settings.IsIgnored(objectType, property, null))
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize "+property.Name+" : is ignored by settings");
                        continue;
                    }

                    if (property.GetIndexParameters().Length != 0)
                    {
                        //if (Settings.DebugMode)
                        //	Console.WriteLine ("Cannot serialize "+property.Name+" : is indexed");
                        continue;
                    }


                    // use Attributes here to control naming
                    string propertyName = JsonNameAttribute.GetJsonName(property);
                    if (String.IsNullOrEmpty(propertyName))
                    {
                        propertyName = property.Name;
                    }

                    propList.Add(new KeyValuePair <string, PropertyInfo>(propertyName, property));
                }

                tp = tp.BaseType;
            }

            outFields = fieldList.ToArray();
            outProps  = propList.ToArray();

            pair = new KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]> (outFields, outProps);

            writingMaps[objectType] = pair;
        }
Пример #26
0
        private static object CoerceType(Type targetType, object value, int index, bool allowNullValueTypes)
        {
            bool isNullable = JsonReader.IsNullable(targetType);

            if (value == null)
            {
                if (allowNullValueTypes &&
                    targetType.IsValueType &&
                    !isNullable)
                {
                    throw new JsonDeserializationException(String.Format(JsonReader.ErrorNullValueType, targetType.FullName), index);
                }
                return(value);
            }

            if (isNullable)
            {
                // nullable types have a real underlying struct
                Type[] genericArgs = targetType.GetGenericArguments();
                if (genericArgs.Length == 1)
                {
                    targetType = genericArgs[0];
                }
            }

            Type actualType = value.GetType();

            if (targetType.IsAssignableFrom(actualType))
            {
                return(value);
            }

            if (targetType.IsEnum)
            {
                if (!Enum.IsDefined(targetType, value))
                {
                    // if isn't a defined value perhaps it is the JsonName
                    foreach (FieldInfo field in targetType.GetFields())
                    {
                        string jsonName = JsonNameAttribute.GetJsonName(field);
                        if (((string)value).Equals(jsonName))
                        {
                            value = field.Name;
                            break;
                        }
                    }
                }

                if (value is String)
                {
                    return(Enum.Parse(targetType, (string)value));
                }
                else
                {
                    return(Convert.ChangeType(value, targetType));
                }
            }

            if (actualType.IsArray && !targetType.IsArray)
            {
                return(JsonReader.CoerceArray(targetType, actualType, value, index, allowNullValueTypes));
            }

            if (value is String)
            {
                if (targetType == typeof(DateTime))
                {
                    DateTime date;
                    if (DateTime.TryParse(
                            (string)value,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                            out date))
                    {
                        return(date);
                    }
                }
                else if (targetType == typeof(Guid))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Guid((string)value));
                }
                else if (targetType == typeof(Uri))
                {
                    Uri uri;
                    if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                    {
                        return(uri);
                    }
                }
                else if (targetType == typeof(Version))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Version((string)value));
                }
            }

            else if (targetType == typeof(TimeSpan))
            {
                return(new TimeSpan((long)JsonReader.CoerceType(typeof(Int64), value, index, allowNullValueTypes)));
            }

            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter.CanConvertFrom(actualType))
            {
                return(converter.ConvertFrom(value));
            }

            converter = TypeDescriptor.GetConverter(actualType);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }

            return(Convert.ChangeType(value, targetType));
        }
Пример #27
0
        /** Creates a member map for the type */
        private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
        {
            Dictionary <string, MemberInfo> memberMap;

            if (this.MemberMapCache.TryGetValue(objectType, out memberMap))
            {
                // map was stored in cache
                return(memberMap);
            }

            // create a new map
            memberMap = new Dictionary <string, MemberInfo>();

            // load properties into property map
            PropertyInfo[] properties = objectType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo info in properties)
            {
                if (!info.CanRead || !info.CanWrite)
                {
                    continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // load public fields into property map
            FieldInfo[] fields = objectType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo info in fields)
            {
                if (!info.IsPublic && info.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length == 0)
                {
                    continue;
                }

                if (JsonIgnoreAttribute.IsJsonIgnore(info))
                {
                    continue;
                }

                string jsonName = JsonNameAttribute.GetJsonName(info);
                if (String.IsNullOrEmpty(jsonName))
                {
                    memberMap[info.Name] = info;
                }
                else
                {
                    memberMap[jsonName] = info;
                }
            }

            // store in cache for repeated usage
            this.MemberMapCache[objectType] = memberMap;

            return(memberMap);
        }
Пример #28
0
        internal object CoerceType(Type targetType, object value)
        {
            bool isNullable = TypeCoercionUtility.IsNullable(targetType);

            if (value == null)
            {
                if (!allowNullValueTypes &&
                    targetType.IsValueType &&
                    !isNullable)
                {
                    throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, targetType.FullName));
                }
                return(value);
            }

            if (isNullable)
            {
                // nullable types have a real underlying struct
                Type[] genericArgs = targetType.GetGenericArguments();
                if (genericArgs.Length == 1)
                {
                    targetType = genericArgs[0];
                }
            }

            Type actualType = value.GetType();

            if (targetType.IsAssignableFrom(actualType))
            {
                return(value);
            }

            if (targetType.IsEnum)
            {
                if (value is String)
                {
                    if (!Enum.IsDefined(targetType, value))
                    {
                        // if isn't a defined value perhaps it is the JsonName
                        foreach (FieldInfo field in targetType.GetFields())
                        {
                            string jsonName = JsonNameAttribute.GetJsonName(field);
                            if (((string)value).Equals(jsonName))
                            {
                                value = field.Name;
                                break;
                            }
                        }
                    }

                    return(Enum.Parse(targetType, (string)value));
                }
                else
                {
                    value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                    return(Enum.ToObject(targetType, value));
                }
            }

            if (value is IDictionary)
            {
                Dictionary <string, MemberInfo> memberMap;
                return(this.CoerceType(targetType, (IDictionary)value, out memberMap));
            }

            if (typeof(IEnumerable).IsAssignableFrom(targetType) &&
                typeof(IEnumerable).IsAssignableFrom(actualType))
            {
                return(this.CoerceList(targetType, actualType, (IEnumerable)value));
            }

            if (value is String)
            {
                if (targetType == typeof(DateTime))
                {
                    DateTime date;

                    // If this is a crazy server date string, clean up the server junk.
                    if (((string)value).StartsWith("/Date(") && ((string)value).EndsWith(")/"))
                    {
                        date  = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                        value = ((string)value).Replace("/Date(", "").Replace(")/", "").Replace("+0000", "");
                        date  = date.AddMilliseconds(long.Parse((string)value));
                        return(date);
                    }

                    // Try a regular DateTime parse
                    if (DateTime.TryParse(
                            (string)value,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                            out date))
                    {
                        return(date);
                    }
                }
                else if (targetType == typeof(Guid))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Guid((string)value));
                }
                else if (targetType == typeof(Char))
                {
                    if (((string)value).Length == 1)
                    {
                        return(((string)value)[0]);
                    }
                }
                else if (targetType == typeof(Uri))
                {
                    Uri uri;
                    if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                    {
                        return(uri);
                    }
                }
                else if (targetType == typeof(Version))
                {
                    // try-catch is pointless since will throw upon generic conversion
                    return(new Version((string)value));
                }
            }
            else if (targetType == typeof(TimeSpan))
            {
                return(new TimeSpan((long)this.CoerceType(typeof(Int64), value)));
            }

            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter.CanConvertFrom(actualType))
            {
                return(converter.ConvertFrom(value));
            }

            converter = TypeDescriptor.GetConverter(actualType);
            if (converter.CanConvertTo(targetType))
            {
                return(converter.ConvertTo(value, targetType));
            }

            try
            {
                // fall back to basics
                return(Convert.ChangeType(value, targetType));
            }
            catch (Exception ex)
            {
                throw new JsonTypeCoercionException(
                          String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex);
            }
        }
Пример #29
0
        protected virtual void WriteObject(object value, Type type)
        {
            bool flag = false;

            this.Writer.Write('{');
            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(string.Format("The maxiumum depth of {0} was exceeded. Check for cycles in object graph.", this.settings.MaxDepth));
            }
            try
            {
                if (!string.IsNullOrEmpty(this.settings.TypeHintName))
                {
                    if (flag)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        flag = true;
                    }
                    this.WriteObjectProperty(this.settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name);
                }
                bool flag2 = type.IsGenericType && type.Name.StartsWith("<>f__AnonymousType");
                foreach (PropertyInfo info in type.GetProperties())
                {
                    if ((info.CanRead && (info.CanWrite || flag2)) && !this.IsIgnored(type, info, value))
                    {
                        object obj2 = info.GetValue(value, null);
                        if (!this.IsDefaultValue(info, obj2))
                        {
                            if (flag)
                            {
                                this.WriteObjectPropertyDelim();
                            }
                            else
                            {
                                flag = true;
                            }
                            string jsonName = JsonNameAttribute.GetJsonName(info);
                            if (string.IsNullOrEmpty(jsonName))
                            {
                                jsonName = info.Name;
                            }
                            this.WriteObjectProperty(jsonName, obj2);
                        }
                    }
                }
                foreach (FieldInfo info2 in type.GetFields())
                {
                    if ((info2.IsPublic && !info2.IsStatic) && !this.IsIgnored(type, info2, value))
                    {
                        object obj3 = info2.GetValue(value);
                        if (!this.IsDefaultValue(info2, obj3))
                        {
                            if (flag)
                            {
                                this.WriteObjectPropertyDelim();
                                this.WriteLine();
                            }
                            else
                            {
                                flag = true;
                            }
                            string name = JsonNameAttribute.GetJsonName(info2);
                            if (string.IsNullOrEmpty(name))
                            {
                                name = info2.Name;
                            }
                            this.WriteObjectProperty(name, obj3);
                        }
                    }
                }
            }
            finally
            {
                this.depth--;
            }
            if (flag)
            {
                this.WriteLine();
            }
            this.Writer.Write('}');
        }