Exemple #1
0
            public void ReturnsPropertyValueForSucceededDeserialization()
            {
                var    serializationObject = SerializationObject.SucceededToDeserialize(typeof(SerializationObject), SerializationMemberGroup.CatelProperty, "property", 42);
                object propertyValue       = serializationObject.MemberValue;

                Assert.AreEqual(42, propertyValue);
            }
Exemple #2
0
        /// <summary>
        /// Deserializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        /// <returns>The <see cref="SerializationObject"/> representing the deserialized value or result.</returns>
        protected override SerializationObject DeserializeMember(ISerializationContext <BinarySerializationContextInfo> context, MemberValue memberValue)
        {
            var serializationContext = context.Context;
            var memberValues         = serializationContext.MemberValues;

            var finalMemberValue = (from x in memberValues
                                    where string.Equals(x.Name, memberValue.Name, StringComparison.Ordinal)
                                    select x).FirstOrDefault();

            if (finalMemberValue != null)
            {
                if (finalMemberValue.Value is string && ShouldSerializeUsingParseAndToString(memberValue, false))
                {
                    var tempValue = memberValue.Value;
                    memberValue.Value = finalMemberValue.Value;

                    var parsedValue = DeserializeUsingObjectParse(context, memberValue);
                    if (parsedValue != null)
                    {
                        finalMemberValue.Value = parsedValue;
                    }
                    else
                    {
                        memberValue.Value = tempValue;
                    }
                }

                return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, finalMemberValue.Value));
            }

            return(SerializationObject.FailedToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name));
        }
Exemple #3
0
        /// <summary>
        /// Deserializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        /// <returns>The <see cref="SerializationObject"/> representing the deserialized value or result.</returns>
        protected override SerializationObject DeserializeMember(ISerializationContext <XmlSerializationContextInfo> context, MemberValue memberValue)
        {
            var modelType = context.ModelType;
            var element   = context.Context.Element;

            try
            {
                var propertyDataManager = PropertyDataManager.Default;
                if (propertyDataManager.IsPropertyNameMappedToXmlAttribute(modelType, memberValue.Name))
                {
                    var mappedPropertyName = propertyDataManager.MapPropertyNameToXmlAttributeName(modelType, memberValue.Name);

                    //Log.Debug("Deserializing property {0}.{1} as xml attribute '{2}'", modelType.FullName, memberValue.Name, mappedPropertyName);

                    foreach (var childAttribute in element.Attributes())
                    {
                        if (string.Equals(mappedPropertyName, childAttribute.Name.LocalName))
                        {
                            var value = GetObjectFromXmlAttribute(childAttribute, memberValue);
                            return(SerializationObject.SucceededToDeserialize(modelType, memberValue.MemberGroup, memberValue.Name, value));
                        }
                    }
                }
                else
                {
                    string elementName = memberValue.Name;

                    if (propertyDataManager.IsPropertyNameMappedToXmlElement(modelType, memberValue.Name))
                    {
                        elementName = propertyDataManager.MapPropertyNameToXmlElementName(modelType, memberValue.Name);
                    }

                    //Log.Debug("Deserializing property {0}.{1} as xml element '{2}'", modelType.FullName, memberValue.Name, elementName);

                    foreach (var childElement in element.Elements())
                    {
                        if (string.Equals(elementName, childElement.Name.LocalName))
                        {
                            var value = GetObjectFromXmlElement(context, childElement, memberValue, modelType);
                            return(SerializationObject.SucceededToDeserialize(modelType, memberValue.MemberGroup, memberValue.Name, value));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Debug(ex, "Failed to deserialize '{0}.{1}'", memberValue.ModelType.GetSafeFullName(), memberValue.Name);
            }

            return(SerializationObject.FailedToDeserialize(modelType, memberValue.MemberGroup, memberValue.Name));
        }
        /// <summary>
        /// Deserializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        /// <returns>The <see cref="SerializationObject"/> representing the deserialized value or result.</returns>
        protected override SerializationObject DeserializeMember(ISerializationContext <BinarySerializationContextInfo> context, MemberValue memberValue)
        {
            var serializationContext = context.Context;
            var memberValues         = serializationContext.MemberValues;

            var finalMembervalue = (from x in memberValues
                                    where string.Equals(x.Name, memberValue.Name, StringComparison.Ordinal)
                                    select x).FirstOrDefault();

            if (finalMembervalue != null)
            {
                return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, finalMembervalue.Value));
            }

            return(SerializationObject.FailedToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name));
        }
Exemple #5
0
        /// <summary>
        /// Deserializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        /// <returns>The <see cref="SerializationObject"/> representing the deserialized value or result.</returns>
        protected override SerializationObject DeserializeMember(ISerializationContext <JsonSerializationContextInfo> context, MemberValue memberValue)
        {
            var serializationContext = context.Context;

            var jsonProperties = serializationContext.JsonProperties;

            if (jsonProperties != null)
            {
                if (PreserveReferences)
                {
                    var graphRefIdPropertyName = string.Format("${0}_{1}", memberValue.NameForSerialization, GraphRefId);
                    if (jsonProperties.ContainsKey(graphRefIdPropertyName))
                    {
                        var graphId          = (int)jsonProperties[graphRefIdPropertyName].Value;
                        var referenceManager = context.ReferenceManager;
                        var referenceInfo    = referenceManager.GetInfoById(graphId);
                        if (referenceInfo == null)
                        {
                            Log.Error("Expected to find graph object with id '{0}' in ReferenceManager, but it was not found. Defaulting value for member '{1}' to null", graphId, memberValue.Name);
                            return(null);
                        }

                        return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, referenceInfo.Instance));
                    }
                }

                if (memberValue.MemberGroup == SerializationMemberGroup.Dictionary)
                {
                    var dictionary = CreateModelInstance(memberValue.MemberType) as IDictionary;

                    var keyType   = typeof(object);
                    var valueType = typeof(object);

                    if (memberValue.MemberType.IsGenericTypeEx())
                    {
                        var genericArguments = memberValue.MemberType.GetGenericArgumentsEx();
                        if (genericArguments.Length == 2)
                        {
                            keyType   = genericArguments[0];
                            valueType = genericArguments[1];
                        }
                    }

                    foreach (var jsonPropertyKeyValuePair in jsonProperties)
                    {
                        var jsonProperty = jsonPropertyKeyValuePair.Value;

                        object deserializedItem = null;

                        object key = jsonProperty.Name;
                        if (keyType != typeof(object))
                        {
                            key = StringToObjectHelper.ToRightType(keyType, jsonProperty.Name);
                        }

                        var typeToDeserialize = valueType;
                        if (jsonProperty.Value != null)
                        {
                            if (jsonProperty.Value.Type != JTokenType.Object)
                            {
                                switch (jsonProperty.Value.Type)
                                {
                                case JTokenType.Integer:
                                    typeToDeserialize = typeof(int);
                                    break;

                                case JTokenType.Float:
                                    typeToDeserialize = typeof(float);
                                    break;

                                case JTokenType.String:
                                    typeToDeserialize = typeof(string);
                                    break;

                                case JTokenType.Boolean:
                                    typeToDeserialize = typeof(bool);
                                    break;

                                case JTokenType.Date:
                                    typeToDeserialize = typeof(DateTime);
                                    break;

                                case JTokenType.Guid:
                                    typeToDeserialize = typeof(Guid);
                                    break;

                                case JTokenType.Uri:
                                    typeToDeserialize = typeof(Uri);
                                    break;

                                case JTokenType.TimeSpan:
                                    typeToDeserialize = typeof(TimeSpan);
                                    break;
                                }
                            }
                        }

                        var shouldValueTypeBeHandledByExternalSerializer = ShouldExternalSerializerHandleMember(typeToDeserialize);
                        if (shouldValueTypeBeHandledByExternalSerializer)
                        {
                            deserializedItem = jsonProperty.Value.ToObject(valueType, serializationContext.JsonSerializer);
                        }
                        else
                        {
                            var reader = jsonProperty.Value.CreateReader(context.Configuration);
                            reader.Culture = context.Configuration.Culture;

                            deserializedItem = Deserialize(valueType, reader, context.Configuration);
                        }

                        dictionary[key] = deserializedItem;
                    }

                    return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, dictionary));
                }

                if (jsonProperties.ContainsKey(memberValue.NameForSerialization))
                {
                    var jsonProperty = jsonProperties[memberValue.NameForSerialization];
                    var jsonValue    = jsonProperty.Value;
                    if (jsonValue != null)
                    {
                        object finalMemberValue = null;
                        var    valueType        = memberValue.GetBestMemberType();
                        if (valueType.IsEnumEx())
                        {
                            var enumName = Enum.GetName(valueType, (int)jsonValue);
                            if (!string.IsNullOrWhiteSpace(enumName))
                            {
                                finalMemberValue = Enum.Parse(valueType, enumName, false);
                            }
                        }
                        else
                        {
                            try
                            {
                                var isDeserialized = false;
                                if (jsonValue.Type == JTokenType.String && ShouldSerializeUsingParseAndToString(memberValue, false))
                                {
                                    var tempValue = memberValue.Value;
                                    memberValue.Value = (string)jsonValue;

                                    var parsedValue = DeserializeUsingObjectParse(context, memberValue);
                                    if (parsedValue != null)
                                    {
                                        finalMemberValue = parsedValue;

                                        isDeserialized = true;
                                    }
                                    else
                                    {
                                        memberValue.Value = tempValue;
                                    }
                                }

                                if (!isDeserialized)
                                {
                                    if (ShouldExternalSerializerHandleMember(memberValue))
                                    {
                                        finalMemberValue = jsonValue.ToObject(valueType, serializationContext.JsonSerializer);
                                    }
                                    else if (ShouldSerializeAsCollection(memberValue))
                                    {
                                        finalMemberValue = Deserialize(valueType, jsonProperty.Value.CreateReader(context.Configuration), context.Configuration);
                                    }
                                    else
                                    {
                                        if (jsonValue.HasValues)
                                        {
                                            var finalValueType = valueType;

                                            var typeNameValue = jsonValue.Value <string>(TypeName);
                                            if (!string.IsNullOrWhiteSpace(typeNameValue))
                                            {
                                                finalValueType = TypeCache.GetType(typeNameValue);
                                            }

                                            // Serialize ourselves
                                            finalMemberValue = Deserialize(finalValueType, jsonValue.CreateReader(context.Configuration), context.Configuration);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Debug(ex, "Failed to parse json value for '{0}', treating value as string", memberValue.Name);

                                // As a fallback, interpret as a string (might be a modifier)
                                finalMemberValue = (string)jsonValue;
                            }
                        }

                        if (finalMemberValue != null)
                        {
                            if (PreserveReferences && finalMemberValue.GetType().IsClassType())
                            {
                                var graphIdPropertyName = string.Format("${0}_{1}", memberValue.NameForSerialization, GraphId);
                                if (jsonProperties.ContainsKey(graphIdPropertyName))
                                {
                                    var graphId = (int)jsonProperties[graphIdPropertyName].Value;

                                    var referenceManager = context.ReferenceManager;
                                    referenceManager.RegisterManually(graphId, finalMemberValue);
                                }
                            }

                            return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, finalMemberValue));
                        }
                    }
                }
            }

            var shouldSerializeAsCollection = ShouldSerializeAsCollection(memberValue);

            if (shouldSerializeAsCollection)
            {
                var collection = new List <object>();

                var jArray = context.Context.JsonArray;
                if (jArray != null)
                {
                    var memberType         = memberValue.GetBestMemberType();
                    var collectionItemType = memberType.GetCollectionElementType();

                    var shouldBeHandledByExternalSerializer = ShouldExternalSerializerHandleMember(collectionItemType);

                    foreach (var item in jArray.Children())
                    {
                        object deserializedItem = null;

                        if (shouldBeHandledByExternalSerializer)
                        {
                            deserializedItem = item.ToObject(collectionItemType, serializationContext.JsonSerializer);
                        }
                        else
                        {
                            deserializedItem = Deserialize(collectionItemType, item.CreateReader(context.Configuration), context.Configuration);
                        }

                        collection.Add(deserializedItem);
                    }
                }

                return(SerializationObject.SucceededToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name, collection));
            }

            return(SerializationObject.FailedToDeserialize(context.ModelType, memberValue.MemberGroup, memberValue.Name));
        }
Exemple #6
0
 public void ThrowsArgumentExceptionForNullOrEmptyPropertyName()
 {
     ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => SerializationObject.SucceededToDeserialize(typeof(SerializationObject), SerializationMemberGroup.CatelProperty, null, null));
     ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => SerializationObject.SucceededToDeserialize(typeof(SerializationObject), SerializationMemberGroup.CatelProperty, string.Empty, null));
 }
Exemple #7
0
 public void ThrowsArgumentNullExceptionForNullType()
 {
     ExceptionTester.CallMethodAndExpectException <ArgumentNullException>(() => SerializationObject.SucceededToDeserialize(null, SerializationMemberGroup.CatelProperty, "property", null));
 }