private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue)
        {
            currentValue = null;
            useExistingValue = false;
            propertyContract = null;
            gottenCurrentValue = false;

            if (property.Ignored)
                return true;

            JsonToken tokenType = reader.TokenType;

            if (property.PropertyContract == null)
                property.PropertyContract = GetContractSafe(property.PropertyType);

            ObjectCreationHandling objectCreationHandling =
                property.ObjectCreationHandling.GetValueOrDefault(Serializer._objectCreationHandling);

            if ((objectCreationHandling != ObjectCreationHandling.Replace)
                && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject)
                && property.Readable)
            {
                currentValue = property.ValueProvider.GetValue(target);
                gottenCurrentValue = true;

                if (currentValue != null)
                {
                    propertyContract = GetContractSafe(currentValue.GetType());

                    useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType());
                }
            }

            if (!property.Writable && !useExistingValue)
                return true;

            // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime
            if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null)
                return true;

            // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
            if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
                && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)
                && JsonReader.IsPrimitiveToken(tokenType)
                && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
                return true;

            if (currentValue == null)
            {
                propertyContract = property.PropertyContract;
            }
            else
            {
                propertyContract = GetContractSafe(currentValue.GetType());

                if (propertyContract != property.PropertyContract)
                    propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty);
            }

            return false;
        }
        private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName)
        {
            TypeNameHandling resolvedTypeNameHandling =
                ((member != null) ? member.TypeNameHandling : null)
                ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
                ?? ((containerMember != null) ? containerMember.ItemTypeNameHandling : null)
                ?? Serializer._typeNameHandling;

            if (resolvedTypeNameHandling != TypeNameHandling.None)
            {
                string typeName;
                string assemblyName;
                ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName);

                Type specifiedType;
                try
                {
                    specifiedType = Serializer._binder.BindToType(assemblyName, typeName);
                }
                catch (Exception ex)
                {
                    throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
                }

                if (specifiedType == null)
                    throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName));

                if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved type '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName, specifiedType)), null);

                if (objectType != null
#if !(NET35 || NET20 || PORTABLE40)
                    && objectType != typeof(IDynamicMetaObjectProvider)
#endif
                    && !objectType.IsAssignableFrom(specifiedType))
                    throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));

                objectType = specifiedType;
                contract = GetContractSafe(specifiedType);
            }
        }
        private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target)
        {
            object currentValue;
            bool useExistingValue;
            JsonContract propertyContract;
            bool gottenCurrentValue;

            if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue))
                return false;

            object value;

            if (propertyConverter != null && propertyConverter.CanRead)
            {
                if (!gottenCurrentValue && target != null && property.Readable)
                    currentValue = property.ValueProvider.GetValue(target);

                value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue);
            }
            else
            {
                value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null);
            }

            // always set the value if useExistingValue is false,
            // otherwise also set it if CreateValue returns a new value compared to the currentValue
            // this could happen because of a JsonConverter against the type
            if ((!useExistingValue || value != currentValue)
                && ShouldSetPropertyValue(property, value))
            {
                property.ValueProvider.SetValue(target, value);

                if (property.SetIsSpecified != null)
                {
                    if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                        TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "IsSpecified for property '{0}' on {1} set to true.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null);

                    property.SetIsSpecified(target, true);
                }

                return true;
            }

            // the value wasn't set be JSON was populated onto the existing value
            return useExistingValue;
        }
        private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id)
        {
            id = null;
            newValue = null;

            if (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();

                if (propertyName.Length > 0 && propertyName[0] == '$')
                {
                    // read metadata properties
                    // $type, $id, $ref, etc
                    bool metadataProperty;

                    do
                    {
                        propertyName = reader.Value.ToString();

                        if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal))
                        {
                            CheckedRead(reader);
                            if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
                                throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));

                            string reference = (reader.Value != null) ? reader.Value.ToString() : null;

                            CheckedRead(reader);

                            if (reference != null)
                            {
                                if (reader.TokenType == JsonToken.PropertyName)
                                    throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));

                                newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference);

                                if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
                                    TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null);

                                return true;
                            }
                            else
                            {
                                metadataProperty = true;
                            }
                        }
                        else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))
                        {
                            CheckedRead(reader);
                            string qualifiedTypeName = reader.Value.ToString();

                            ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName);

                            CheckedRead(reader);

                            metadataProperty = true;
                        }
                        else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
                        {
                            CheckedRead(reader);

                            id = (reader.Value != null) ? reader.Value.ToString() : null;

                            CheckedRead(reader);
                            metadataProperty = true;
                        }
                        else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal))
                        {
                            CheckedRead(reader);
                            object list = CreateList(reader, objectType, contract, member, existingValue, id);
                            CheckedRead(reader);
                            newValue = list;
                            return true;
                        }
                        else
                        {
                            metadataProperty = false;
                        }
                    } while (metadataProperty && reader.TokenType == JsonToken.PropertyName);
                }
            }
            return false;
        }
        private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id)
        {
            id = null;
            newValue = null;

            if (reader.TokenType == JsonToken.StartObject)
            {
                JObject current = (JObject)reader._current;

                JToken refToken = current[JsonTypeReflector.RefPropertyName];
                if (refToken != null)
                {
                    if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null)
                        throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null);

                    JToken property = refToken.Parent;
                    JToken additionalContent = null;
                    if (property.Next != null)
                        additionalContent = property.Next;
                    else if (property.Previous != null)
                        additionalContent = property.Previous;

                    string reference = (string)refToken;

                    if (reference != null)
                    {
                        if (additionalContent != null)
                            throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null);

                        newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference);

                        if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
                            TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null);

                        reader.Skip();
                        return true;
                    }
                }
                JToken typeToken = current[JsonTypeReflector.TypePropertyName];
                if (typeToken != null)
                {
                    string qualifiedTypeName = (string)typeToken;
                    JsonReader typeTokenReader = typeToken.CreateReader();
                    CheckedRead(typeTokenReader);
                    ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName);

                    JToken valueToken = current[JsonTypeReflector.ValuePropertyName];
                    if (valueToken != null)
                    {
                        while (true)
                        {
                            CheckedRead(reader);
                            if (reader.TokenType == JsonToken.PropertyName)
                            {
                                if ((string)reader.Value == JsonTypeReflector.ValuePropertyName)
                                    return false;
                            }

                            CheckedRead(reader);
                            reader.Skip();
                        }
                    }
                }
                JToken idToken = current[JsonTypeReflector.IdPropertyName];
                if (idToken != null)
                {
                    id = (string)idToken;
                }
                JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName];
                if (valuesToken != null)
                {
                    JsonReader listReader = valuesToken.CreateReader();
                    CheckedRead(listReader);
                    newValue = CreateList(listReader, objectType, contract, member, existingValue, id);

                    reader.Skip();
                    return true;
                }
            }

            CheckedRead(reader);
            return false;
        }
        private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
        {
            string id;
            object newValue;
            Type resolvedObjectType = objectType;

            if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead)
            {
                var tokenReader = reader as JTokenReader;
                if (tokenReader == null)
                {
                    JToken t = JToken.ReadFrom(reader);
                    tokenReader = (JTokenReader)t.CreateReader();

                    // start
                    CheckedRead(tokenReader);

                    reader = tokenReader;
                }

                if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id))
                    return newValue;
            }
            else
            {
                CheckedRead(reader);
                if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id))
                    return newValue;
            }

            if (HasNoDefinedType(contract))
                return CreateJObject(reader);

            switch (contract.ContractType)
            {
                case JsonContractType.Object:
                {
                    bool createdFromNonDefaultCreator = false;
                    JsonObjectContract objectContract = (JsonObjectContract)contract;
                    object targetObject;
                    // check that if type name handling is being used that the existing value is compatible with the specified type
                    if (existingValue != null && (resolvedObjectType == objectType || resolvedObjectType.IsAssignableFrom(existingValue.GetType())))
                        targetObject = existingValue;
                    else
                        targetObject = CreateNewObject(reader, objectContract, member, containerMember, id, out createdFromNonDefaultCreator);

                    // don't populate if read from non-default creator because the object has already been read
                    if (createdFromNonDefaultCreator)
                        return targetObject;

                    return PopulateObject(targetObject, reader, objectContract, member, id);
                }
                case JsonContractType.Primitive:
                {
                    JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
                    // if the content is inside $value then read past it
                    if (reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal))
                    {
                        CheckedRead(reader);

                        // the token should not be an object because the $type value could have been included in the object
                        // without needing the $value property
                        if (reader.TokenType == JsonToken.StartObject)
                            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType);

                        object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue);

                        CheckedRead(reader);
                        return value;
                    }
                    break;
                }
                case JsonContractType.Dictionary:
                {
                    JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract;
                    object targetDictionary;

                    if (existingValue == null)
                    {
                        bool createdFromNonDefaultCreator;
                        IDictionary dictionary = CreateNewDictionary(reader, dictionaryContract, out createdFromNonDefaultCreator);

                        if (createdFromNonDefaultCreator)
                        {
                            if (id != null)
                                throw JsonSerializationException.Create(reader, "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

                            if (contract.OnSerializingCallbacks.Count > 0)
                                throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

                            if (contract.OnErrorCallbacks.Count > 0)
                                throw JsonSerializationException.Create(reader, "Cannot call OnError on readonly list, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

                            if (dictionaryContract.ParametrizedCreator == null)
                                throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size dictionary: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
                        }

                        PopulateDictionary(dictionary, reader, dictionaryContract, member, id);

                        if (createdFromNonDefaultCreator)
                        {
                            return dictionaryContract.ParametrizedCreator(dictionary);
                        }
                        else if (dictionary is IWrappedDictionary)
                        {
                            return ((IWrappedDictionary)dictionary).UnderlyingDictionary;
                        }

                        targetDictionary = dictionary;
                    }
                    else
                    {
                        targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id);
                    }

                    return targetDictionary;
                }
#if !(NET35 || NET20 || PORTABLE40)
                case JsonContractType.Dynamic:
                    JsonDynamicContract dynamicContract = (JsonDynamicContract)contract;
                    return CreateDynamic(reader, dynamicContract, member, id);
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
                case JsonContractType.Serializable:
                    JsonISerializableContract serializableContract = (JsonISerializableContract)contract;
                    return CreateISerializable(reader, serializableContract, member, id);
#endif
            }

            throw JsonSerializationException.Create(reader, @"Cannot deserialize the current JSON object (e.g. {{""name"":""value""}}) into type '{0}' because the type requires a {1} to deserialize correctly.
To fix this error either change the JSON to a {1} or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
".FormatWith(CultureInfo.InvariantCulture, resolvedObjectType, GetExpectedDescription(contract)));
        }
 private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty)
 {
     JsonConverter converter = null;
     if (memberConverter != null)
     {
         // member attribute converter
         converter = memberConverter;
     }
     else if (containerProperty != null && containerProperty.ItemConverter != null)
     {
         converter = containerProperty.ItemConverter;
     }
     else if (containerContract != null && containerContract.ItemConverter != null)
     {
         converter = containerContract.ItemConverter;
     }
     else if (contract != null)
     {
         JsonConverter matchingConverter;
         if (contract.Converter != null)
             // class attribute converter
             converter = contract.Converter;
         else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null)
             // passed in converters
             converter = matchingConverter;
         else if (contract.InternalConverter != null)
             // internally specified converter
             converter = contract.InternalConverter;
     }
     return converter;
 }
        private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
        {
            if (contract != null && contract.ContractType == JsonContractType.Linq)
                return CreateJToken(reader, contract);

            do
            {
                switch (reader.TokenType)
                {
                    // populate a typed object or generic dictionary/array
                    // depending upon whether an objectType was supplied
                    case JsonToken.StartObject:
                        return CreateObject(reader, objectType, contract, member, containerContract, containerMember, existingValue);
                    case JsonToken.StartArray:
                        return CreateList(reader, objectType, contract, member, existingValue, null);
                    case JsonToken.Integer:
                    case JsonToken.Float:
                    case JsonToken.Boolean:
                    case JsonToken.Date:
                    case JsonToken.Bytes:
                        return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
                    case JsonToken.String:
                        string s = (string)reader.Value;

                        // convert empty string to null automatically for nullable types
                        if (string.IsNullOrEmpty(s) && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable)
                            return null;

                        // string that needs to be returned as a byte array should be base 64 decoded
                        if (objectType == typeof(byte[]))
                            return Convert.FromBase64String(s);

                        return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType);
                    case JsonToken.StartConstructor:
                        string constructorName = reader.Value.ToString();

                        return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType);
                    case JsonToken.Null:
                    case JsonToken.Undefined:
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
                        if (objectType == typeof(DBNull))
                            return DBNull.Value;
#endif

                        return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
                    case JsonToken.Raw:
                        return new JRaw((string)reader.Value);
                    case JsonToken.Comment:
                        // ignore
                        break;
                    default:
                        throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType);
                }
            } while (reader.Read());

            throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
        }