Exemplo n.º 1
0
        private MemberMappingCollection CreateMemberMappings(Type objectType)
        {
            MemberInfo[]            members        = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.Instance);
            MemberMappingCollection memberMappings = new MemberMappingCollection();

            foreach (MemberInfo member in members)
            {
                string mappedName;

                JsonPropertyAttribute propertyAttribute = ReflectionUtils.GetAttribute(typeof(JsonPropertyAttribute), member, true) as JsonPropertyAttribute;
                if (propertyAttribute != null)
                {
                    mappedName = propertyAttribute.PropertyName;
                }
                else
                {
                    mappedName = member.Name;
                }

                bool          ignored       = member.IsDefined(typeof(JsonIgnoreAttribute), true);
                bool          readable      = ReflectionUtils.CanReadMemberValue(member);
                bool          writable      = ReflectionUtils.CanSetMemberValue(member);
                MemberMapping memberMapping = new MemberMapping(mappedName, member, ignored, readable, writable);

                memberMappings.Add(memberMapping);
            }

            return(memberMappings);
        }
Exemplo n.º 2
0
        private MemberMappingCollection CreateMemberMappings(Type objectType)
        {
            MemberSerialization memberSerialization = GetObjectMemberSerialization(objectType);

            List <MemberInfo> members = GetSerializableMembers(objectType);

            if (members == null)
            {
                throw new JsonSerializationException("Null collection of seralizable members returned.");
            }

            MemberMappingCollection memberMappings = new MemberMappingCollection();

            foreach (MemberInfo member in members)
            {
                JsonPropertyAttribute propertyAttribute = ReflectionUtils.GetAttribute <JsonPropertyAttribute>(member, true);
                bool hasIgnoreAttribute = member.IsDefined(typeof(JsonIgnoreAttribute), true);

                string mappedName = (propertyAttribute != null && propertyAttribute.PropertyName != null)
         ? propertyAttribute.PropertyName
         : member.Name;

                bool ignored = (hasIgnoreAttribute ||
                                (memberSerialization == MemberSerialization.OptIn && propertyAttribute == null));

                bool          readable      = ReflectionUtils.CanReadMemberValue(member);
                bool          writable      = ReflectionUtils.CanSetMemberValue(member);
                MemberMapping memberMapping = new MemberMapping(mappedName, member, ignored, readable, writable);

                memberMappings.AddMapping(memberMapping);
            }

            return(memberMappings);
        }
Exemplo n.º 3
0
        protected virtual JsonMemberMapping CreateMemberMapping(MemberSerialization memberSerialization, MemberInfo member)
        {
            JsonPropertyAttribute propertyAttribute = ReflectionUtils.GetAttribute <JsonPropertyAttribute>(member, true);
            bool hasIgnoreAttribute = member.IsDefined(typeof(JsonIgnoreAttribute), true);

            string mappedName = (propertyAttribute != null && propertyAttribute.PropertyName != null)
                            ? propertyAttribute.PropertyName
                            : member.Name;

            string resolvedMappedName = ResolveMappingName(mappedName);

            bool required = (propertyAttribute != null) ? propertyAttribute.IsRequired : false;

            bool ignored = (hasIgnoreAttribute ||
                            (memberSerialization == MemberSerialization.OptIn && propertyAttribute == null));

            bool readable = ReflectionUtils.CanReadMemberValue(member);
            bool writable = ReflectionUtils.CanSetMemberValue(member);

            JsonConverter memberConverter = JsonTypeReflector.GetConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = ReflectionUtils.GetAttribute <DefaultValueAttribute>(member, true);
            object defaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            return(new JsonMemberMapping(resolvedMappedName, member, ignored, readable, writable, memberConverter, defaultValue, required));
        }
Exemplo n.º 4
0
        private static bool CanSetProperty(MemberInfo member)
        {
            if (!ReflectionUtils.CanSetMemberValue(member))
            {
                return(false);
            }
            Type memberUnderlyingType = ReflectionUtils.GetMemberUnderlyingType(member);

            return(TypeHelpers.IsSupportedParameterType(memberUnderlyingType));
        }
        protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty jsonProperty = new JsonProperty();

            jsonProperty.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            jsonProperty.ValueProvider = CreateMemberValueProvider(member);
            SetPropertySettingsFromAttributes(jsonProperty, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute);
            jsonProperty.Readable        = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
            jsonProperty.Writable        = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, hasExplicitAttribute);
            jsonProperty.ShouldSerialize = CreateShouldSerializeTest(member);
            SetIsSpecifiedActions(jsonProperty, member, allowNonPublicAccess);
            return(jsonProperty);
        }
Exemplo n.º 6
0
        private void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName)
        {
            if (!reader.Read())
            {
                throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
            }

            MemberInfo[] memberCollection = targetType.GetMember(memberName);
            Type         memberType;
            object       value;

            // test if a member with memberName exists on the type
            // otherwise test if target is a dictionary and assign value with the key if it is
            if (!CollectionUtils.IsNullOrEmpty <MemberInfo>(memberCollection))
            {
                MemberInfo member = targetType.GetMember(memberName)[0];

                // ignore member if it is readonly
                if (!ReflectionUtils.CanSetMemberValue(member))
                {
                    return;
                }

                if (member.IsDefined(typeof(JsonIgnoreAttribute), true))
                {
                    return;
                }

                // get the member's underlying type
                memberType = ReflectionUtils.GetMemberUnderlyingType(member);

                value = GetObject(reader, memberType);

                ReflectionUtils.SetMemberValue(member, target, value);
            }
            else if (typeof(IDictionary).IsAssignableFrom(targetType))
            {
                // attempt to get the IDictionary's type
                memberType = ReflectionUtils.GetTypedDictionaryValueType(target.GetType());

                value = GetObject(reader, memberType);

                ((IDictionary)target).Add(memberName, value);
            }
            else
            {
                throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
            }
        }
        protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty jsonProperty = new JsonProperty();

            jsonProperty.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            jsonProperty.ValueProvider = this.CreateMemberValueProvider(member);
            bool flag;
            bool canSetReadOnly;

            this.SetPropertySettingsFromAttributes(jsonProperty, member, member.Name, member.DeclaringType, memberSerialization, out flag, out canSetReadOnly);
            jsonProperty.Readable        = ReflectionUtils.CanReadMemberValue(member, flag);
            jsonProperty.Writable        = ReflectionUtils.CanSetMemberValue(member, flag, canSetReadOnly);
            jsonProperty.ShouldSerialize = this.CreateShouldSerializeTest(member);
            this.SetIsSpecifiedActions(jsonProperty, member, flag);
            return(jsonProperty);
        }
Exemplo n.º 8
0
        private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo memberInfo = (MemberInfo)member.DeclaringType.GetProperty(member.Name + "Specified") ?? (MemberInfo)member.DeclaringType.GetField(member.Name + "Specified");

            if (memberInfo == null || ReflectionUtils.GetMemberUnderlyingType(memberInfo) != typeof(bool))
            {
                return;
            }
            Func <object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet <object>(memberInfo);

            property.GetIsSpecified = (Predicate <object>)(o => (bool)specifiedPropertyGet(o));
            if (!ReflectionUtils.CanSetMemberValue(memberInfo, allowNonPublicAccess, false))
            {
                return;
            }
            property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet <object>(memberInfo);
        }
        private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo memberInfo = member.DeclaringType.GetProperty(member.Name + "Specified");

            if (memberInfo == null)
            {
                memberInfo = member.DeclaringType.GetField(member.Name + "Specified");
            }
            if (memberInfo != null && ReflectionUtils.GetMemberUnderlyingType(memberInfo) == typeof(bool))
            {
                Func <object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet <object>(memberInfo);
                property.GetIsSpecified = ((object o) => (bool)specifiedPropertyGet(o));
                if (ReflectionUtils.CanSetMemberValue(memberInfo, allowNonPublicAccess, canSetReadOnly: false))
                {
                    property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet <object>(memberInfo);
                }
            }
        }
Exemplo n.º 10
0
        private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo field = member.DeclaringType.GetProperty(string.Concat(member.Name, "Specified"));

            if (field == null)
            {
                field = member.DeclaringType.GetField(string.Concat(member.Name, "Specified"));
            }
            if (field == null || ReflectionUtils.GetMemberUnderlyingType(field) != typeof(bool))
            {
                return;
            }
            Func <object, object> func = JsonTypeReflector.ReflectionDelegateFactory.CreateGet <object>(field);

            property.GetIsSpecified = (object o) => (bool)func(o);
            if (ReflectionUtils.CanSetMemberValue(field, allowNonPublicAccess, false))
            {
                property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet <object>(field);
            }
        }
        private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo memberInfo = member.get_DeclaringType().GetProperty(member.get_Name() + "Specified");

            if (memberInfo == null)
            {
                memberInfo = member.get_DeclaringType().GetField(member.get_Name() + "Specified");
            }
            if (memberInfo == null || ReflectionUtils.GetMemberUnderlyingType(memberInfo) != typeof(bool))
            {
                return;
            }
            Func <object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet <object>(memberInfo);

            property.GetIsSpecified = ((object o) => (bool)specifiedPropertyGet.Invoke(o));
            if (ReflectionUtils.CanSetMemberValue(memberInfo, allowNonPublicAccess, false))
            {
                property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet <object>(memberInfo);
            }
        }
Exemplo n.º 12
0
        private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
        {
            MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix);

            if (specifiedMember == null)
            {
                specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix);
            }

            if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool))
            {
                return;
            }

            Func <object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet <object>(specifiedMember);

            property.GetIsSpecified = o => (bool)specifiedPropertyGet(o);

            if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false))
            {
                property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet <object>(specifiedMember);
            }
        }
Exemplo n.º 13
0
        protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = new JsonProperty();

            property.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            property.DeclaringType = member.DeclaringType;
            property.ValueProvider = this.CreateMemberValueProvider(member);
            bool allowNonPublicAccess;

            this.SetPropertySettingsFromAttributes(property, ReflectionUtils.GetCustomAttributeProvider((object)member), member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess);
            if (memberSerialization != MemberSerialization.Fields)
            {
                property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
                property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, property.HasMemberAttribute);
            }
            else
            {
                property.Readable = true;
                property.Writable = true;
            }
            property.ShouldSerialize = this.CreateShouldSerializeTest(member);
            this.SetIsSpecifiedActions(property, member, allowNonPublicAccess);
            return(property);
        }
Exemplo n.º 14
0
        protected override List <MemberInfo> GetSerializableMembers(Type objectType)
        {
            bool ignoreSerializableAttribute = this.IgnoreSerializableAttribute;
            MemberSerialization objectMemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType,
                                                                                                           ignoreSerializableAttribute);
            List <MemberInfo> allMembers = (
                from m in
                ReflectionUtils.GetFieldsAndProperties(objectType,
                                                       BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                where
                !ReflectionUtils.IsIndexedProperty(m)
                select m).ToList();
            List <MemberInfo> serializableMembers = new List <MemberInfo>();

            if (objectMemberSerialization != MemberSerialization.Fields)
            {
                DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
                List <MemberInfo>     defaultMembers        = (
                    from m in ReflectionUtils.GetFieldsAndProperties(objectType, this.DefaultMembersSearchFlags)
                    where
                    !ReflectionUtils.IsIndexedProperty(m)
                    select m).ToList();
                foreach (MemberInfo memberInfo in allMembers)
                {
                    //DataTransObjectBase
                    if (memberInfo.DeclaringType == typeof(DataTransObjectBase))
                    {
                        continue;
                    }
                    //contextdto
                    if (memberInfo.DeclaringType != null && memberInfo.DeclaringType.IsSubclassOf(typeof(ProxyBase)))
                    {
                        var memberName = memberInfo.Name.ToLower(CultureInfo.CurrentCulture);
                        if (memberName == "contextdto" || memberName == "targetorgcode" || memberName == "targetorgname" ||
                            memberName.EndsWith("_skey"))
                        {
                            continue;
                        }
                    }
                    //BusinessEntity.EntityKey
                    if (memberInfo.DeclaringType != null &&
                        (memberInfo.DeclaringType == typeof(ObjectKeyX) ||
                         memberInfo.DeclaringType.IsSubclassOf(typeof(ObjectKeyX))))
                    {
                        var memberName = memberInfo.Name.ToLower(CultureInfo.CurrentCulture);
                        if (memberName == "entitytype" || memberName == "serializablekeys")
                        {
                            continue;
                        }
                    }
                    var isDTOType = false;
                    switch (memberInfo.MemberType())
                    {
                    case MemberTypes.Field:
                        var fieldInfo = (FieldInfo)memberInfo;
                        if (fieldInfo.DeclaringType != null &&
                            fieldInfo.FieldType.IsSubclassOf(typeof(DataTransObjectBase)))
                        {
                            isDTOType = true;
                        }
                        break;

                    case MemberTypes.Property:
                        var propertyInfo = (PropertyInfo)memberInfo;
                        if (propertyInfo.DeclaringType != null &&
                            propertyInfo.DeclaringType.IsSubclassOf(typeof(DataTransObjectBase)))
                        {
                            isDTOType = true;
                        }
                        break;
                    }
                    if (isDTOType)
                    {
                        var memberName = memberInfo.Name.ToLower(CultureInfo.CurrentCulture);
                        if (memberName == "combinename" || memberName.StartsWith("multi_") ||
                            memberName.EndsWith("_skey"))
                        {
                            continue;
                        }
                    }
                    if (!ReflectionUtils.CanSetMemberValue(memberInfo, true, true))
                    {
                        continue;
                    }
                    if (this.SerializeCompilerGeneratedMembers ||
                        !memberInfo.IsDefined(typeof(CompilerGeneratedAttribute), true))
                    {
                        if (defaultMembers.Contains(memberInfo))
                        {
                            serializableMembers.Add(memberInfo);
                        }
                        else
                        {
                            if (JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(memberInfo) != null)
                            {
                                serializableMembers.Add(memberInfo);
                            }
                            else
                            {
                                if (dataContractAttribute != null &&
                                    JsonTypeReflector.GetAttribute <DataMemberAttribute>(memberInfo) != null)
                                {
                                    serializableMembers.Add(memberInfo);
                                }
                                else
                                {
                                    if (objectMemberSerialization == MemberSerialization.Fields &&
                                        memberInfo.MemberType() == MemberTypes.Field)
                                    {
                                        serializableMembers.Add(memberInfo);
                                    }
                                }
                            }
                        }
                    }
                }
                Type type;
                if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out type))
                {
                    serializableMembers = serializableMembers.Where(this.ShouldSerializeEntityMember).ToList();
                }
            }
            else
            {
                foreach (MemberInfo member in allMembers)
                {
                    var fieldInfo = member as FieldInfo;
                    if (fieldInfo != null && !fieldInfo.IsStatic)
                    {
                        var memberName = fieldInfo.Name.ToLower(CultureInfo.CurrentCulture);
                        if (memberName == "sysstate" || memberName.StartsWith("multi_") ||
                            memberName.EndsWith("_skey"))
                        {
                            continue;
                        }
                        serializableMembers.Add(member);
                    }
                }
            }
            return(serializableMembers);
        }
        object ConvertToObject(IDictionary <string, object> dict, Type type)
        {
            if (_typeResolver != null)
            {
                if (dict.Keys.Contains(SerializedTypeNameKey))
                {
                    // already Evaluated
                    type = _typeResolver.ResolveType((string)dict [SerializedTypeNameKey]);
                }
            }

            if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(IDictionary <,>)))
                {
                    Type[] arguments = type.GetGenericArguments();
                    if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof(object) && arguments [0] != typeof(string)))
                    {
                        throw new InvalidOperationException(
                                  "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
                    }
                    if (type.IsAbstract)
                    {
                        Type dictType = typeof(Dictionary <,>);
                        type = dictType.MakeGenericType(arguments [0], arguments [1]);
                    }
                }
            }
            else if (type.IsAssignableFrom(typeof(IDictionary)))
            {
                type = typeof(Dictionary <string, object>);
            }

            object target = Activator.CreateInstance(type, true);

            foreach (KeyValuePair <string, object> entry in dict)
            {
                object value = entry.Value;
                if (target is IDictionary)
                {
                    Type valueType = ReflectionUtils.GetTypedDictionaryValueType(type);
                    if (value != null && valueType == typeof(System.Object))
                    {
                        valueType = value.GetType();
                    }

                    ((IDictionary)target).Add(entry.Key, ConvertToType(value, valueType));
                    continue;
                }
                MemberInfo [] memberCollection = type.GetMember(entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (memberCollection == null || memberCollection.Length == 0)
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                MemberInfo member = memberCollection [0];

                if (!ReflectionUtils.CanSetMemberValue(member))
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                Type memberType = ReflectionUtils.GetMemberUnderlyingType(member);

                if (memberType.IsInterface)
                {
                    if (memberType.IsGenericType)
                    {
                        memberType = ResolveGenericInterfaceToType(memberType);
                    }
                    else
                    {
                        memberType = ResolveInterfaceToType(memberType);
                    }

                    if (memberType == null)
                    {
                        throw new InvalidOperationException("Unable to deserialize a member, as its type is an unknown interface.");
                    }
                }

                ReflectionUtils.SetMemberValue(member, target, ConvertToType(value, memberType));
            }

            return(target);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="contract">The member's declaring types <see cref="JsonObjectContract"/>.</param>
        /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
        /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
        protected virtual JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member)
        {
            JsonProperty property = new JsonProperty();

            property.PropertyType = ReflectionUtils.GetMemberUnderlyingType(member);
#if !PocketPC
            property.ValueProvider = new DynamicValueProvider(member);
#else
            property.ValueProvider = new ReflectionValueProvider(member);
#endif

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter = JsonTypeReflector.GetJsonConverter(member, property.PropertyType);

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetAttribute <DataMemberAttribute>(member);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member);
            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(member) != null);

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = member.Name;
            }

            property.PropertyName = ResolvePropertyName(mappedName);

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
            }
#endif
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (contract.MemberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
#if !PocketPC && !NET20
                                 && dataMemberAttribute == null
#endif
                                ));

            property.Readable = ReflectionUtils.CanReadMemberValue(member);
            property.Writable = ReflectionUtils.CanSetMemberValue(member);

            property.MemberConverter = JsonTypeReflector.GetJsonConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(member);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            return(property);
        }
        object ConvertToObject(IDictionary <string, object> dict, Type type)
        {
            if (_typeResolver != null)
            {
                if (dict is JsonSerializer.DeserializerLazyDictionary)
                {
                    JsonSerializer.DeserializerLazyDictionary lazyDict = (JsonSerializer.DeserializerLazyDictionary)dict;
                    object first = lazyDict.PeekFirst();
                    if (first != null)
                    {
                        KeyValuePair <string, object> firstPair = (KeyValuePair <string, object>)first;
                        if (firstPair.Key == SerializedTypeNameKey)
                        {
                            type = _typeResolver.ResolveType((string)firstPair.Value);
                        }
                        else
                        {
                            dict = EvaluateDictionary(dict);
                        }
                    }
                }

                if (!(dict is JsonSerializer.DeserializerLazyDictionary) && dict.Keys.Contains(SerializedTypeNameKey))
                {
                    // already Evaluated
                    type = _typeResolver.ResolveType((string)dict [SerializedTypeNameKey]);
                }
            }

            object target = Activator.CreateInstance(type, true);

            foreach (KeyValuePair <string, object> entry in dict)
            {
                object value = entry.Value;
                if (target is IDictionary)
                {
                    ((IDictionary)target).Add(entry.Key, ConvertToType(ReflectionUtils.GetTypedDictionaryValueType(type), value));
                    continue;
                }
                MemberInfo [] memberCollection = type.GetMember(entry.Key);
                if (memberCollection == null || memberCollection.Length == 0)
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                MemberInfo member = memberCollection [0];

                if (!ReflectionUtils.CanSetMemberValue(member))
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                ReflectionUtils.SetMemberValue(member, target, ConvertToType(ReflectionUtils.GetMemberUnderlyingType(member), value));
            }

            return(target);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="memberSerialization">The member's parent <see cref="MemberSerialization"/>.</param>
        /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
        /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
        protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = new JsonProperty();

            property.PropertyType  = ReflectionUtils.GetMemberUnderlyingType(member);
            property.ValueProvider = CreateMemberValueProvider(member);

            // resolve converter for property
            // the class type might have a converter but the property converter takes presidence
            property.Converter = JsonTypeReflector.GetJsonConverter(member, property.PropertyType);

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetAttribute <DataMemberAttribute>(member);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member);
            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(member) != null);

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = member.Name;
            }

            property.PropertyName = ResolvePropertyName(mappedName);

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.Required;
            }
#if !PocketPC && !NET20
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
            }
#endif
            else
            {
                property.Required = Required.Default;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (memberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
#if !PocketPC && !NET20
                                 && dataMemberAttribute == null
#endif
                                ));

            bool allowNonPublicAccess = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (propertyAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#if !PocketPC && !NET20
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
            }
#endif

            property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
            property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess);

            property.MemberConverter = JsonTypeReflector.GetJsonConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(member);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling      = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling   = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling  = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
            property.TypeNameHandling       = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
            property.IsReference            = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            property.ShouldSerialize = CreateShouldSerializeTest(member);

            return(property);
        }
Exemplo n.º 19
0
        /*private void SetObjectMemberFull(JsonReader reader, object target, Type targetType, string memberName)
         * {
         *  if (!reader.Read())
         *      throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
         *
         *  MemberInfo[] memberCollection = targetType.GetMember(memberName);
         *  Type memberType;
         *  object value;
         *
         *  // test if a member with memberName exists on the type
         *  // otherwise test if target is a dictionary and assign value with the key if it is
         *  if (!CollectionUtils.IsNullOrEmpty<MemberInfo>(memberCollection))
         *  {
         *      MemberInfo member = targetType.GetMember(memberName)[0];
         *
         *      // ignore member if it is readonly
         *      if (!ReflectionUtils.CanSetMemberValue(member))
         *          return;
         *
         *      if (member.IsDefined(typeof(JsonIgnoreAttribute), true))
         *          return;
         *
         *      // get the member's underlying type
         *      memberType = ReflectionUtils.GetMemberUnderlyingType(member);
         *
         *      value = GetObject(reader, memberType);
         *
         *      ReflectionUtils.SetMemberValue(member, target, value);
         *  }
         *  else if (typeof(IDictionary).IsAssignableFrom(targetType))
         *  {
         *      // attempt to get the IDictionary's type
         *      memberType = ReflectionUtils.GetTypedDictionaryValueType(target.GetType());
         *
         *      value = GetObject(reader, memberType);
         *
         *      ((IDictionary)target).Add(memberName, value);
         *  }
         *  else
         *  {
         *      throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
         *  }
         * }*/

        private static void SetObjectMember(JsonReader reader, object target, Type targetType, string memberName)
        {
            if (!reader.Read())
            {
                throw new JsonSerializationException(string.Format("Unexpected end when setting {0}'s value.", memberName));
            }

            Type   memberType;
            object value;

            if (0 != String.CompareOrdinal(memberName, "List"))
            {
                MemberInfo[] memberCollection = targetType.GetMember(memberName);

                // test if a member with memberName exists on the type
                // otherwise test if target is a dictionary and assign value with the key if it is
                if (!CollectionUtils.IsNullOrEmpty <MemberInfo>(memberCollection))
                {
                    MemberInfo member = targetType.GetMember(memberName)[0];

                    // ignore member if it is readonly
                    if (!ReflectionUtils.CanSetMemberValue(member))
                    {
                        return;
                    }

                    if (member.IsDefined(typeof(System.Xml.Serialization.XmlIgnoreAttribute), true))
                    {
                        return;
                    }

                    // get the member's underlying type
                    memberType = ReflectionUtils.GetMemberUnderlyingType(member);

                    value = GetObject(reader, memberType);

                    ReflectionUtils.SetMemberValue(member, target, value);
                }
                else if (typeof(IDictionary).IsAssignableFrom(targetType))
                {
                    // attempt to get the IDictionary's type
                    memberType = ReflectionUtils.GetTypedDictionaryValueType(target.GetType());

                    value = GetObject(reader, memberType);

                    ((IDictionary)target).Add(memberName, value);
                }
                else
                {
                    throw new JsonSerializationException(string.Format("Could not find member '{0}' on object of type '{1}'", memberName, targetType.GetType().Name));
                }
            }
            else
            {
                if (targetType.IsInstanceOfType(typeof(IList)))
                {
                    if (reader.TokenType == JsonToken.StartObject)
                    {
                        value = PopulateList(reader, targetType);
                    }
                    else
                    {
                        value = GetObject(reader, targetType);
                    }
                }
                else if (ReflectionUtils.IsSubClass(targetType, typeof(List <>)))
                {
                    if (reader.TokenType == JsonToken.StartObject)
                    {
                        value = PopulateList(reader, targetType.UnderlyingSystemType.BaseType);
                    }
                    else
                    {
                        value = GetObject(reader, targetType.UnderlyingSystemType.BaseType);
                    }
                }
                else
                {
                    value = null;
                }

                if (value != null && value is IEnumerable)
                {
                    foreach (object item in (IEnumerable)value)
                    {
                        ((IList)target).Add(item);
                    }
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="contract">The member's declaring types <see cref="JsonObjectContract"/>.</param>
        /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
        /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
        protected virtual JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member)
        {
            JsonProperty property = new JsonProperty();

            property.Member = member;

#if !PocketPC && !SILVERLIGHT && !MONO
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);

            DataMemberAttribute dataMemberAttribute;
            if (dataContractAttribute != null)
            {
                dataMemberAttribute = JsonTypeReflector.GetAttribute <DataMemberAttribute>(member);
            }
            else
            {
                dataMemberAttribute = null;
            }
#endif

            JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member);
            bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(member) != null);

            string mappedName;
            if (propertyAttribute != null && propertyAttribute.PropertyName != null)
            {
                mappedName = propertyAttribute.PropertyName;
            }
#if !PocketPC && !SILVERLIGHT && !MONO
            else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
            {
                mappedName = dataMemberAttribute.Name;
            }
#endif
            else
            {
                mappedName = member.Name;
            }

            property.PropertyName = ResolvePropertyName(mappedName);

            if (propertyAttribute != null)
            {
                property.Required = propertyAttribute.IsRequired;
            }
#if !PocketPC && !SILVERLIGHT && !MONO
            else if (dataMemberAttribute != null)
            {
                property.Required = dataMemberAttribute.IsRequired;
            }
#endif
            else
            {
                property.Required = false;
            }

            property.Ignored = (hasIgnoreAttribute ||
                                (contract.MemberSerialization == MemberSerialization.OptIn &&
                                 propertyAttribute == null
#if !PocketPC && !SILVERLIGHT && !MONO
                                 && dataMemberAttribute == null
#endif
                                ));

            property.Readable = ReflectionUtils.CanReadMemberValue(member);
            property.Writable = ReflectionUtils.CanSetMemberValue(member);

            property.MemberConverter = JsonTypeReflector.GetConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));

            DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(member);
            property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;

            property.NullValueHandling     = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
            property.DefaultValueHandling  = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
            property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
            property.IsReference           = (propertyAttribute != null) ? propertyAttribute._isReference : null;

            return(property);
        }