コード例 #1
0
ファイル: ObjectSerializer.cs プロジェクト: patrickprz/neural
        private object PopulateInstance(IndexedDictionary <string, object> container, object instance)
        {
            if (instance == null && objectType == typeof(object))
            {
                return(container);
            }

            if (instance == null)
            {
                instance = objectTypeDescription.CreateInstance();
            }

            foreach (var member in this.objectTypeDescription.Members)
            {
                var memberName   = member.Name;
                var memberType   = member.ValueType;
                var defaultValue = member.DefaultValue;

                if (defaultValue == null || container.ContainsKey(memberName))
                {
                    continue;
                }

                if (defaultValue.GetType() == memberType)
                {
                    container[memberName] = defaultValue;
                }
                else if ("[]".Equals(defaultValue) || "{}".Equals(defaultValue))
                {
                    container[memberName] = memberType.IsArray
                                                ? Array.CreateInstance(memberType.GetElementType(), 0)
                                                : Activator.CreateInstance(memberType);
                }
                else if (defaultValue is string)
                {
                    container[memberName] = Json.Deserialize(memberType, (string)defaultValue, context);
                }
                else
                {
                    container[memberName] = Convert.ChangeType(defaultValue, memberType, context.Format);
                }
            }


            foreach (var kv in container)
            {
                var memberName = kv.Key;
                var value      = kv.Value;
                var member     = default(DataMemberDescription);

                if (!this.TryGetMember(memberName, out member))
                {
                    continue;
                }

                try
                {
                    member.SetValue(instance, value);
                }
                catch (Exception e)
                {
                    throw new SerializationException(string.Format("Failed to set member '{0}' to value '{1}' of type {2}.\r\n More detailed information in inner exception.",
                                                                   memberName, value, value != null ? value.GetType().FullName : "<null>"), e);
                }
            }

            if (this.baseTypeSerializer != null)
            {
                this.baseTypeSerializer.PopulateInstance(container, instance);
            }

            return(instance);
        }