Contract details for a Type used by the JsonSerializer.
Inheritance: Newtonsoft.Json.Serialization.JsonContainerContract
Exemple #1
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract collectionContract, JsonContract collectionValueContract)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            JsonConverter converter;

            if ((((converter = (member != null) ? member.Converter : null) != null) ||
                 ((converter = (collectionContract != null) ? collectionContract.ItemConverter : null) != null) ||
                 ((converter = valueContract.Converter) != null) ||
                 ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) ||
                 ((converter = valueContract.InternalConverter) != null)) &&
                converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract, collectionContract, collectionValueContract);
                return;
            }

            switch (valueContract.ContractType)
            {
            case JsonContractType.Object:
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionContract, collectionValueContract);
                break;

            case JsonContractType.Array:
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionContract, collectionValueContract);
                break;

            case JsonContractType.Primitive:
                SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionContract, collectionValueContract);
                break;

            case JsonContractType.String:
                SerializeString(writer, value, (JsonStringContract)valueContract);
                break;

            case JsonContractType.Dictionary:
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionContract, collectionValueContract);
                break;

#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
            case JsonContractType.Dynamic:
                SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, collectionContract, collectionValueContract);
                break;
#endif
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
            case JsonContractType.Serializable:
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, collectionContract, collectionValueContract);
                break;
#endif
            case JsonContractType.Linq:
                ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
                break;
            }
        }
        private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
        {
            IWrappedDictionary dictionary = contract.CreateWrapper(contract.DefaultCreator());

            PopulateDictionary(dictionary, reader, contract, id);

            return(dictionary.UnderlyingDictionary);
        }
        protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract jsonDictionaryContract = new JsonDictionaryContract(objectType);

            this.InitializeContract(jsonDictionaryContract);
            jsonDictionaryContract.PropertyNameResolver = new Func <string, string>(this.ResolvePropertyName);
            return(jsonDictionaryContract);
        }
        protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract contract = new JsonDictionaryContract(objectType);

            this.method_7(contract);
            contract.PropertyNameResolver = new Func <string, string>(this.ResolvePropertyName);
            return(contract);
        }
        /// <summary>
        /// Creates a <see cref="JsonDictionaryContract"/> for the given type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
        protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract contract = new JsonDictionaryContract(objectType);

            InitializeContract(contract);

            return(contract);
        }
        protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract jsonDictionaryContract = new JsonDictionaryContract(objectType);

            InitializeContract(jsonDictionaryContract);
            jsonDictionaryContract.PropertyNameResolver = ResolvePropertyName;
            return(jsonDictionaryContract);
        }
        private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
        {
            IWrappedDictionary dictionary = CollectionUtils.CreateDictionaryWrapper(Activator.CreateInstance(contract.DictionaryTypeToCreate));

            PopulateDictionary(dictionary, reader, contract, id);

            return(dictionary.UnderlyingDictionary);
        }
Exemple #8
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else
            {
                JsonConverter converter;
                if (((converter = member != null ? member.Converter : (JsonConverter)null) != null || (converter = containerProperty != null ? containerProperty.ItemConverter : (JsonConverter)null) != null || ((converter = containerContract != null ? containerContract.ItemConverter : (JsonConverter)null) != null || (converter = valueContract.Converter) != null || ((converter = this.Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null || (converter = valueContract.InternalConverter) != null))) && converter.CanWrite)
                {
                    this.SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
                }
                else
                {
                    switch (valueContract.ContractType)
                    {
                    case JsonContractType.Object:
                        this.SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
                        break;

                    case JsonContractType.Array:
                        JsonArrayContract contract1 = (JsonArrayContract)valueContract;
                        if (!contract1.IsMultidimensionalArray)
                        {
                            this.SerializeList(writer, contract1.CreateWrapper(value), contract1, member, containerContract, containerProperty);
                            break;
                        }
                        else
                        {
                            this.SerializeMultidimensionalArray(writer, (Array)value, contract1, member, containerContract, containerProperty);
                            break;
                        }

                    case JsonContractType.Primitive:
                        this.SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
                        break;

                    case JsonContractType.String:
                        this.SerializeString(writer, value, (JsonStringContract)valueContract);
                        break;

                    case JsonContractType.Dictionary:
                        JsonDictionaryContract contract2 = (JsonDictionaryContract)valueContract;
                        this.SerializeDictionary(writer, contract2.CreateWrapper(value), contract2, member, containerContract, containerProperty);
                        break;

                    case JsonContractType.Serializable:
                        this.SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
                        break;

                    case JsonContractType.Linq:
                        ((JToken)value).WriteTo(writer, this.Serializer.Converters != null ? Enumerable.ToArray <JsonConverter>((IEnumerable <JsonConverter>) this.Serializer.Converters) : (JsonConverter[])null);
                        break;
                    }
                }
            }
        }
Exemple #9
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter converter = (member != null) ? member.Converter : null;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((converter != null ||
                 ((converter = valueContract.Converter) != null) ||
                 ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) ||
                 ((converter = valueContract.InternalConverter) != null)) &&
                converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract);
            }
            else if (valueContract is JsonPrimitiveContract)
            {
                SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonStringContract)
            {
                SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                if (!arrayContract.IsMultidimensionalArray)
                {
                    SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
                }
                else
                {
                    SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, collectionValueContract);
                }
            }
            else if (valueContract is JsonLinqContract)
            {
                ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
            }
#if !((UNITY_WINRT && !UNITY_EDITOR) || (UNITY_WP8 || UNITY_WP_8_1))
            else if (valueContract is JsonISerializableContract)
            {
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
#endif
        }
Exemple #10
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter converter = (member != null) ? member.Converter : null;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((converter != null ||
                 ((converter = valueContract.Converter) != null) ||
                 ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) ||
                 ((converter = valueContract.InternalConverter) != null)) &&
                converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract);
            }
            else if (valueContract is JsonPrimitiveContract)
            {
                writer.WriteValue(value);
            }
            else if (valueContract is JsonStringContract)
            {
                SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
            }
            else if (valueContract is JsonLinqContract)
            {
                ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
            }
#if !SILVERLIGHT && !PocketPC
            else if (valueContract is JsonISerializableContract)
            {
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE)
            else if (valueContract is JsonDynamicContract)
            {
                SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract);
            }
#endif
        }
Exemple #11
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter converter = (member != null) ? member.Converter : null;

            if (converter == null && JsonSerializerSettings.DefaultEnumSerializationHandling == EnumSerializationHandling.Name && value is Enum)
            {
                converter = new StringEnumConverter();
            }

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((converter != null ||
                 ((converter = valueContract.Converter) != null) ||
                 ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) ||
                 ((converter = valueContract.InternalConverter) != null)) &&
                converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract);
            }
            else if (valueContract is JsonPrimitiveContract)
            {
                SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonStringContract)
            {
                SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
            }
            else if (valueContract is JsonLinqContract)
            {
                ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
            }
            else if (valueContract is JsonISerializableContract)
            {
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
        }
Exemple #12
0
 private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
 {
     if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || base.Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
     {
         object             dictionary        = contract.DefaultCreator();
         IWrappedDictionary wrappedDictionary = contract.CreateWrapper(dictionary);
         PopulateDictionary(wrappedDictionary, reader, contract, id);
         return(wrappedDictionary.UnderlyingDictionary);
     }
     throw new JsonSerializationException("Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
 }
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter jsonConverter = (member == null) ? null : member.Converter;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            if ((jsonConverter != null || (jsonConverter = valueContract.Converter) != null || (jsonConverter = base.Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null || (jsonConverter = valueContract.InternalConverter) != null) && jsonConverter.CanWrite)
            {
                this.SerializeConvertable(writer, jsonConverter, value, valueContract);
            }
            else if (valueContract is JsonPrimitiveContract)
            {
                this.SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonStringContract)
            {
                this.SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                this.SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)valueContract;
                this.SerializeDictionary(writer, jsonDictionaryContract.CreateWrapper(value), jsonDictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                JsonArrayContract jsonArrayContract = (JsonArrayContract)valueContract;
                if (!jsonArrayContract.IsMultidimensionalArray)
                {
                    this.SerializeList(writer, jsonArrayContract.CreateWrapper(value), jsonArrayContract, member, collectionValueContract);
                }
                else
                {
                    this.SerializeMultidimensionalArray(writer, (Array)value, jsonArrayContract, member, collectionValueContract);
                }
            }
            else if (valueContract is JsonLinqContract)
            {
                ((JToken)value).WriteTo(writer, (base.Serializer.Converters == null) ? null : base.Serializer.Converters.ToArray <JsonConverter>());
            }
            else if (valueContract is JsonISerializableContract)
            {
                this.SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
            object             obj = (wrappedDictionary != null) ? wrappedDictionary.UnderlyingDictionary : values;

            this.OnSerializing(writer, contract, obj);
            this._serializeStack.Add(obj);
            this.WriteObjectStart(writer, obj, contract, member, collectionContract, containerProperty);
            if (contract.ItemContract == null)
            {
                contract.ItemContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }
            if (contract.KeyContract == null)
            {
                contract.KeyContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }
            int top = writer.Top;

            foreach (DictionaryEntry dictionaryEntry in values)
            {
                bool   escape;
                string text = this.GetPropertyName(writer, dictionaryEntry.Key, contract.KeyContract, out escape);
                text = ((contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(text) : text);
                try
                {
                    object       value        = dictionaryEntry.Value;
                    JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(value);
                    if (this.ShouldWriteReference(value, null, jsonContract, contract, member))
                    {
                        writer.WritePropertyName(text, escape);
                        this.WriteReference(writer, value);
                    }
                    else if (this.CheckForCircularReference(writer, value, null, jsonContract, contract, member))
                    {
                        writer.WritePropertyName(text, escape);
                        this.SerializeValue(writer, value, jsonContract, null, contract, member);
                    }
                }
                catch (Exception ex)
                {
                    if (!base.IsErrorHandled(obj, contract, text, null, writer.ContainerPath, ex))
                    {
                        throw;
                    }
                    this.HandleError(writer, top);
                }
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            this.OnSerialized(writer, contract, obj);
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract)
        {
            contract.InvokeOnSerializing(values);

            SerializeStack.Add(values);
            writer.WriteStartObject();

            bool isReference = contract.IsReference ?? HasFlag(_serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);

            if (isReference)
            {
                writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                writer.WriteValue(_serializer.ReferenceResolver.GetReference(values));
            }
            if (HasFlag(_serializer.TypeNameHandling, TypeNameHandling.Objects))
            {
                WriteTypeProperty(writer, values.GetType());
            }

            foreach (DictionaryEntry entry in values)
            {
                string propertyName = entry.Key.ToString();
                object value        = entry.Value;

                if (ShouldWriteReference(value, null))
                {
                    writer.WritePropertyName(propertyName);
                    WriteReference(writer, value);
                }
                else
                {
                    if (!CheckForCircularReference(value, null))
                    {
                        continue;
                    }

                    writer.WritePropertyName(propertyName);
                    SerializeValue(writer, value, null);
                }
            }

            writer.WriteEndObject();
            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values);
        }
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

              SerializeStack.Add(values.UnderlyingDictionary);
              writer.WriteStartObject();

              bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
              if (isReference)
              {
            writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
            writer.WriteValue(Serializer.ReferenceResolver.GetReference(values.UnderlyingDictionary));
              }
              if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
              {
            WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
              }

              JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

              int initialDepth = writer.Top;

              // Mono Unity 3.0 fix
              IDictionary d = values;

              foreach (DictionaryEntry entry in d)
              {
            string propertyName = GetPropertyName(entry);

            try
            {
              object value = entry.Value;
              JsonContract valueContract = GetContractSafe(value);

              if (ShouldWriteReference(value, null, valueContract))
              {
            writer.WritePropertyName(propertyName);
            WriteReference(writer, value);
              }
              else
              {
            if (!CheckForCircularReference(value, null, contract))
              continue;

            writer.WritePropertyName(propertyName);

            SerializeValue(writer, value, valueContract, null, childValuesContract);
              }
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
            HandleError(writer, initialDepth);
              else
            throw;
            }
              }

              writer.WriteEndObject();
              SerializeStack.RemoveAt(SerializeStack.Count - 1);

              contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
        }
Exemple #17
0
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            bool               flag;
            object             underlyingDictionary;
            IWrappedDictionary wrappedDictionaries = values as IWrappedDictionary;

            if (wrappedDictionaries != null)
            {
                underlyingDictionary = wrappedDictionaries.UnderlyingDictionary;
            }
            else
            {
                underlyingDictionary = values;
            }
            object obj = underlyingDictionary;

            this.OnSerializing(writer, contract, obj);
            this._serializeStack.Add(obj);
            this.WriteObjectStart(writer, obj, contract, member, collectionContract, containerProperty);
            if (contract.ItemContract == null)
            {
                contract.ItemContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }
            if (contract.KeyContract == null)
            {
                contract.KeyContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }
            int top = writer.Top;
            IDictionaryEnumerator enumerator = values.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    DictionaryEntry entry        = enumerator.Entry;
                    string          propertyName = this.GetPropertyName(writer, entry.Key, contract.KeyContract, out flag);
                    propertyName = (contract.DictionaryKeyResolver != null ? contract.DictionaryKeyResolver(propertyName) : propertyName);
                    try
                    {
                        object       value             = entry.Value;
                        JsonContract finalItemContract = contract.FinalItemContract ?? this.GetContractSafe(value);
                        if (this.ShouldWriteReference(value, null, finalItemContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, flag);
                            this.WriteReference(writer, value);
                        }
                        else if (this.CheckForCircularReference(writer, value, null, finalItemContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, flag);
                            this.SerializeValue(writer, value, finalItemContract, null, contract, member);
                        }
                        else
                        {
                            continue;
                        }
                    }
                    catch (Exception exception)
                    {
                        if (!base.IsErrorHandled(obj, contract, propertyName, null, writer.ContainerPath, exception))
                        {
                            throw;
                        }
                        else
                        {
                            this.HandleError(writer, top);
                        }
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
                else
                {
                }
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            this.OnSerialized(writer, contract, obj);
        }
    public object CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract)
    {
      object dictionary;

      if (contract.DefaultCreator != null &&
        (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
        dictionary = contract.DefaultCreator();
      else
        throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

      return dictionary;
    }
        /// <summary>
        /// Creates a <see cref="JsonDictionaryContract"/> for the given type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
        protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract contract = new JsonDictionaryContract(objectType);
              InitializeContract(contract);

              return contract;
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
            object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

            if (contract.KeyContract == null)
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));

            int initialDepth = writer.Top;

            foreach (DictionaryEntry entry in values)
            {
                bool escape;
                string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);

                propertyName = (contract.PropertyNameResolver != null)
                    ? contract.PropertyNameResolver(propertyName)
                    : propertyName;

                try
                {
                    object value = entry.Value;
                    JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract, member))
                    {
                        writer.WritePropertyName(propertyName, escape);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            continue;

                        writer.WritePropertyName(propertyName, escape);

                        SerializeValue(writer, value, valueContract, null, contract, member);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                        HandleError(writer, initialDepth);
                    else
                        throw;
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
Exemple #21
0
 private Schema CreateDictionarySchema(JsonDictionaryContract dictionaryContract)
 {
     var valueType = dictionaryContract.DictionaryValueType ?? typeof(object);
     return new Schema
         {
             type = "object",
             additionalProperties = CreateInlineSchema(valueType)
         };
 }
Exemple #22
0
        private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue)
        {
            CheckedRead(reader);

            string id = null;

            if (reader.TokenType == JsonToken.PropertyName)
            {
                bool specialProperty;

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

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

                        string reference = reader.Value.ToString();

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

                        return(Serializer.ReferenceResolver.ResolveReference(reference));
                    }
                    else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))
                    {
                        CheckedRead(reader);
                        string qualifiedTypeName = reader.Value.ToString();

                        CheckedRead(reader);

                        if ((((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling) != 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 new JsonSerializationException("Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
                            }

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

                            if (objectType != null && !objectType.IsAssignableFrom(specifiedType))
                            {
                                throw new JsonSerializationException("Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));
                            }

                            objectType = specifiedType;
                            contract   = GetContractSafe(specifiedType);
                        }
                        specialProperty = true;
                    }
                    else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
                    {
                        CheckedRead(reader);

                        id = reader.Value.ToString();
                        CheckedRead(reader);
                        specialProperty = true;
                    }
                    else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal))
                    {
                        CheckedRead(reader);
                        object list = CreateList(reader, objectType, contract, member, existingValue, id);
                        CheckedRead(reader);
                        return(list);
                    }
                    else
                    {
                        specialProperty = false;
                    }
                } while (specialProperty &&
                         reader.TokenType == JsonToken.PropertyName);
            }

            if (!HasDefinedType(objectType))
            {
                return(CreateJObject(reader));
            }

            if (contract == null)
            {
                throw new JsonSerializationException("Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }

            JsonDictionaryContract dictionaryContract = contract as JsonDictionaryContract;

            if (dictionaryContract != null)
            {
                if (existingValue == null)
                {
                    return(CreateAndPopulateDictionary(reader, dictionaryContract, id));
                }

                return(PopulateDictionary(dictionaryContract.CreateWrapper(existingValue), reader, dictionaryContract, id));
            }

            JsonObjectContract objectContract = contract as JsonObjectContract;

            if (objectContract != null)
            {
                if (existingValue == null)
                {
                    return(CreateAndPopulateObject(reader, objectContract, id));
                }

                return(PopulateObject(existingValue, reader, objectContract, id));
            }

#if !SILVERLIGHT && !PocketPC
            JsonISerializableContract serializableContract = contract as JsonISerializableContract;
            if (serializableContract != null)
            {
                return(CreateISerializable(reader, serializableContract, id));
            }
#endif

#if !(NET35 || NET20 || SILVERLIGHT)
            JsonDynamicContract dynamicContract = contract as JsonDynamicContract;
            if (dynamicContract != null)
            {
                return(CreateDynamic(reader, dynamicContract, id));
            }
#endif

            throw new JsonSerializationException("Cannot deserialize JSON object into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
        }
        private IDictionary PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, string id)
        {
            if (id != null)
            {
                Serializer.ReferenceResolver.AddReference(id, dictionary.UnderlyingDictionary);
            }

            contract.InvokeOnDeserializing(dictionary.UnderlyingDictionary);

            int initialDepth = reader.Depth;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    object keyValue = EnsureType(reader.Value, contract.DictionaryKeyType);
                    CheckedRead(reader);

                    try
                    {
                        dictionary.Add(keyValue, CreateValue(reader, contract.DictionaryValueType, GetContractSafe(contract.DictionaryValueType), null, null));
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(dictionary, contract, keyValue, ex))
                        {
                            HandleError(reader, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    break;

                case JsonToken.EndObject:
                    contract.InvokeOnDeserialized(dictionary.UnderlyingDictionary);

                    return(dictionary);

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (reader.Read());

            throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
        private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
        {
            IWrappedDictionary dictionary = CollectionUtils.CreateDictionaryWrapper(Activator.CreateInstance(contract.DictionaryTypeToCreate));

              PopulateDictionary(dictionary, reader, contract, id);

              return dictionary.UnderlyingDictionary;
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
            object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
            IDictionaryEnumerator e = values.GetEnumerator();
            try
            {
                while (e.MoveNext())
                {
                    DictionaryEntry entry = e.Entry;

                    bool escape;
                    string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);

                    propertyName = (contract.DictionaryKeyResolver != null)
                        ? contract.DictionaryKeyResolver(propertyName)
                        : propertyName;

                    try
                    {
                        object value = entry.Value;
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, escape);
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                continue;
                            }

                            writer.WritePropertyName(propertyName, escape);

                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            finally
            {
                (e as IDisposable)?.Dispose();
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
 private object PopulateDictionary(IWrappedDictionary wrappedDictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id)
 {
   object underlyingDictionary = wrappedDictionary.UnderlyingDictionary;
   if (id != null)
     this.AddReference(reader, id, underlyingDictionary);
   contract.InvokeOnDeserializing(underlyingDictionary, this.Serializer.Context);
   int depth = reader.Depth;
   if (contract.KeyContract == null)
     contract.KeyContract = this.GetContractSafe(contract.DictionaryKeyType);
   if (contract.ItemContract == null)
     contract.ItemContract = this.GetContractSafe(contract.DictionaryValueType);
   JsonConverter jsonConverter = contract.ItemConverter ?? this.GetConverter(contract.ItemContract, (JsonConverter) null, (JsonContainerContract) contract, containerProperty);
   bool flag = false;
   do
   {
     switch (reader.TokenType)
     {
       case JsonToken.PropertyName:
         object keyValue = reader.Value;
         try
         {
           try
           {
             keyValue = this.EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType);
           }
           catch (Exception ex)
           {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.", (IFormatProvider) CultureInfo.InvariantCulture, reader.Value, (object) contract.DictionaryKeyType), ex);
           }
           if (!this.ReadForType(reader, contract.ItemContract, jsonConverter != null))
             throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
           object obj = jsonConverter == null || !jsonConverter.CanRead ? this.CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, (JsonProperty) null, (JsonContainerContract) contract, containerProperty, (object) null) : jsonConverter.ReadJson(reader, contract.DictionaryValueType, (object) null, (JsonSerializer) this.GetInternalSerializer());
           wrappedDictionary[keyValue] = obj;
           goto case JsonToken.Comment;
         }
         catch (Exception ex)
         {
           if (this.IsErrorHandled(underlyingDictionary, (JsonContract) contract, keyValue, reader.Path, ex))
           {
             this.HandleError(reader, true, depth);
             goto case JsonToken.Comment;
           }
           else
             throw;
         }
       case JsonToken.Comment:
         continue;
       case JsonToken.EndObject:
         flag = true;
         goto case JsonToken.Comment;
       default:
         throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + (object) reader.TokenType);
     }
   }
   while (!flag && reader.Read());
   if (!flag)
     this.ThrowUnexpectedEndException(reader, (JsonContract) contract, underlyingDictionary, "Unexpected end when deserializing object.");
   contract.InvokeOnDeserialized(underlyingDictionary, this.Serializer.Context);
   return underlyingDictionary;
 }
 public object CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract)
 {
   if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || this.Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
     return contract.DefaultCreator();
   else
     throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unable to find a default constructor to use for type {0}.", (IFormatProvider) CultureInfo.InvariantCulture, (object) contract.UnderlyingType));
 }
    public object CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool isTemporaryDictionary)
    {
      object dictionary;

      if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
      {
        dictionary = contract.DefaultCreator();
        isTemporaryDictionary = false;
      }
      else if (contract.IsReadOnlyDictionary)
      {
        dictionary = contract.CreateTemporaryDictionary();
        isTemporaryDictionary = true;
      }
      else
      {
        throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
      }

      return dictionary;
    }
        private IDictionary PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, string id)
        {
            if (id != null)
            _serializer.ReferenceResolver.AddReference(id, dictionary.UnderlyingDictionary);

              contract.InvokeOnDeserializing(dictionary.UnderlyingDictionary);

              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            object keyValue = EnsureType(reader.Value, contract.DictionaryKeyType);
            CheckedRead(reader);

            dictionary.Add(keyValue, CreateValue(reader, contract.DictionaryValueType, null, null));
            break;
              case JsonToken.EndObject:
            contract.InvokeOnDeserialized(dictionary.UnderlyingDictionary);

            return dictionary;
              default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
            }
              } while (reader.Read());

              throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
Exemple #30
0
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

            SerializeStack.Add(values.UnderlyingDictionary);
            writer.WriteStartObject();

            bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);

            if (isReference)
            {
                writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
            }
            if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
            {
                WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
            }

            JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

            int initialDepth = writer.Top;

            // Mono Unity 3.0 fix
            IDictionary d = values;

            foreach (DictionaryEntry entry in d)
            {
                string propertyName = GetPropertyName(entry);

                propertyName = (contract.PropertyNameResolver != null)
                         ? contract.PropertyNameResolver(propertyName)
                         : propertyName;

                try
                {
                    object       value         = entry.Value;
                    JsonContract valueContract = GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        writer.WritePropertyName(propertyName);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(value, null, contract))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName);

                        SerializeValue(writer, value, valueContract, null, childValuesContract);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            writer.WriteEndObject();
            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
        }
Exemple #31
0
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedDictionary wrappedDictionary    = values as IWrappedDictionary;
            object             underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            foreach (DictionaryEntry entry in values)
            {
                bool   escape;
                string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);

                propertyName = (contract.DictionaryKeyResolver != null)
                    ? contract.DictionaryKeyResolver(propertyName)
                    : propertyName;

                try
                {
                    object       value         = entry.Value;
                    JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract, member))
                    {
                        writer.WritePropertyName(propertyName, escape);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName, escape);

                        SerializeValue(writer, value, valueContract, null, contract, member);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
        private object PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, string id)
        {
            if (id != null)
            Serializer.ReferenceResolver.AddReference(id, dictionary.UnderlyingDictionary);

              contract.InvokeOnDeserializing(dictionary.UnderlyingDictionary, Serializer.Context);

              int initialDepth = reader.Depth;

              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            object keyValue = EnsureType(reader.Value, contract.DictionaryKeyType);
            CheckedRead(reader);

            try
            {
              dictionary[keyValue] = CreateValue(reader, contract.DictionaryValueType, GetContractSafe(contract.DictionaryValueType), null, null);
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(dictionary, contract, keyValue, ex))
                HandleError(reader, initialDepth);
              else
                throw;
            }
            break;
              case JsonToken.EndObject:
            contract.InvokeOnDeserialized(dictionary.UnderlyingDictionary, Serializer.Context);

            return dictionary.UnderlyingDictionary;
              default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
            }
              } while (reader.Read());

              throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
        private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id)
        {
            IWrappedDictionary wrappedDictionary = dictionary as IWrappedDictionary;
              object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : dictionary;

              if (id != null)
            AddReference(reader, id, underlyingDictionary);

              OnDeserializing(reader, contract, underlyingDictionary);

              int initialDepth = reader.Depth;

              if (contract.KeyContract == null)
            contract.KeyContract = GetContractSafe(contract.DictionaryKeyType);

              if (contract.ItemContract == null)
            contract.ItemContract = GetContractSafe(contract.DictionaryValueType);

              JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty);
              PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract)contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty;

              bool finished = false;
              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            object keyValue = reader.Value;
            try
            {
              try
              {
                object dt;
                // this is for correctly reading ISO and MS formatted dictionary keys
                if ((keyTypeCode == PrimitiveTypeCode.DateTime || keyTypeCode == PrimitiveTypeCode.DateTimeNullable)
                  && DateTimeUtils.TryParseDateTime(keyValue.ToString(), DateParseHandling.DateTime, reader.DateTimeZoneHandling, out dt))
                {
                  keyValue = dt;
                }
            #if !NET20
                else if ((keyTypeCode == PrimitiveTypeCode.DateTimeOffset || keyTypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
                  && DateTimeUtils.TryParseDateTime(keyValue.ToString(), DateParseHandling.DateTimeOffset, reader.DateTimeZoneHandling, out dt))
                {
                  keyValue = dt;
                }
            #endif
                else
                {
                  keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType);
                }
              }
              catch (Exception ex)
              {
                throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
              }

              if (!ReadForType(reader, contract.ItemContract, dictionaryValueConverter != null))
                throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");

              object itemValue;
              if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead)
                itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null);
              else
                itemValue = CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null);

              dictionary[keyValue] = itemValue;
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(underlyingDictionary, contract, keyValue, reader as IJsonLineInfo, reader.Path, ex))
                HandleError(reader, true, initialDepth);
              else
                throw;
            }
            break;
              case JsonToken.Comment:
            break;
              case JsonToken.EndObject:
            finished = true;
            break;
              default:
            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
            }
              } while (!finished && reader.Read());

              if (!finished)
            ThrowUnexpectedEndException(reader, contract, underlyingDictionary, "Unexpected end when deserializing object.");

              OnDeserialized(reader, contract, underlyingDictionary);
              return underlyingDictionary;
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract)
        {
            contract.InvokeOnSerializing(values);

              SerializeStack.Add(values);
              writer.WriteStartObject();

              bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
              if (isReference)
              {
            writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
            writer.WriteValue(Serializer.ReferenceResolver.GetReference(values));
              }
              if (HasFlag(Serializer.TypeNameHandling, TypeNameHandling.Objects))
              {
            WriteTypeProperty(writer, values.GetType());
              }

              int initialDepth = writer.Top;

              foreach (DictionaryEntry entry in values)
              {
            string propertyName = GetPropertyName(entry);

            try
            {
              object value = entry.Value;
              JsonContract valueContract = GetContractSafe(value);

              if (ShouldWriteReference(value, null, valueContract))
              {
            writer.WritePropertyName(propertyName);
            WriteReference(writer, value);
              }
              else
              {
            if (!CheckForCircularReference(value, null))
              continue;

            writer.WritePropertyName(propertyName);

            SerializeValue(writer, value, null, valueContract);
              }
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(values, contract, propertyName, ex))
            HandleError(writer, initialDepth);
              else
            throw;
            }
              }

              writer.WriteEndObject();
              SerializeStack.RemoveAt(SerializeStack.Count - 1);

              contract.InvokeOnSerialized(values);
        }
        private Schema CreateDictionarySchema(JsonDictionaryContract dictionaryContract)
        {
            var keyType = dictionaryContract.DictionaryKeyType ?? typeof(object);
            var valueType = dictionaryContract.DictionaryValueType ?? typeof(object);

            if (keyType.IsEnum)
            {
                return new Schema
                {
                    type = "object",
                    properties = Enum.GetNames(keyType).ToDictionary(
                        (name) => dictionaryContract.PropertyNameResolver(name),
                        (name) => CreateInlineSchema(valueType)
                    )
                };
            }
            else
            {
                return new Schema
                {
                    type = "object",
                    additionalProperties = CreateInlineSchema(valueType)
                };
            }
        }
Exemple #36
0
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, this.Serializer.Context);
            this._serializeStack.Add(values.UnderlyingDictionary);
            this.WriteObjectStart(writer, values.UnderlyingDictionary, (JsonContract)contract, member, collectionContract, containerProperty);
            if (contract.ItemContract == null)
            {
                contract.ItemContract = this.Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }
            int top = writer.Top;

            foreach (DictionaryEntry entry in (IDictionary)values)
            {
                string propertyName = this.GetPropertyName(entry);
                string name         = contract.PropertyNameResolver != null?contract.PropertyNameResolver(propertyName) : propertyName;

                try
                {
                    object       obj          = entry.Value;
                    JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(obj);
                    if (this.ShouldWriteReference(obj, (JsonProperty)null, jsonContract, (JsonContainerContract)contract, member))
                    {
                        writer.WritePropertyName(name);
                        this.WriteReference(writer, obj);
                    }
                    else if (this.CheckForCircularReference(writer, obj, (JsonProperty)null, jsonContract, (JsonContainerContract)contract, member))
                    {
                        writer.WritePropertyName(name);
                        this.SerializeValue(writer, obj, jsonContract, (JsonProperty)null, (JsonContainerContract)contract, member);
                    }
                }
                catch (Exception ex)
                {
                    if (this.IsErrorHandled(values.UnderlyingDictionary, (JsonContract)contract, (object)name, writer.ContainerPath, ex))
                    {
                        this.HandleError(writer, top);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            contract.InvokeOnSerialized(values.UnderlyingDictionary, this.Serializer.Context);
        }
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter converter;

            JsonConverter[] array;
            if (member == null)
            {
                converter = null;
            }
            else
            {
                converter = member.Converter;
            }
            JsonConverter jsonConverter = converter;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            if (jsonConverter == null)
            {
                JsonConverter converter1 = valueContract.Converter;
                jsonConverter = converter1;
                if (converter1 == null)
                {
                    JsonConverter matchingConverter = base.Serializer.GetMatchingConverter(valueContract.UnderlyingType);
                    jsonConverter = matchingConverter;
                    if (matchingConverter == null)
                    {
                        JsonConverter internalConverter = valueContract.InternalConverter;
                        jsonConverter = internalConverter;
                        if (internalConverter == null)
                        {
                            goto Label0;
                        }
                    }
                }
            }
            if (jsonConverter.CanWrite)
            {
                this.SerializeConvertable(writer, jsonConverter, value, valueContract);
                return;
            }
            if (valueContract is JsonPrimitiveContract)
            {
                this.SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonStringContract)
            {
                this.SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                this.SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)valueContract;
                this.SerializeDictionary(writer, jsonDictionaryContract.CreateWrapper(value), jsonDictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                JsonArrayContract jsonArrayContract = (JsonArrayContract)valueContract;
                if (jsonArrayContract.IsMultidimensionalArray)
                {
                    this.SerializeMultidimensionalArray(writer, (Array)value, jsonArrayContract, member, collectionValueContract);
                }
                else
                {
                    this.SerializeList(writer, jsonArrayContract.CreateWrapper(value), jsonArrayContract, member, collectionValueContract);
                }
            }
            else if (valueContract is JsonLinqContract)
            {
                JToken     jTokens    = (JToken)value;
                JsonWriter jsonWriter = writer;
                if (base.Serializer.Converters == null)
                {
                    array = null;
                }
                else
                {
                    array = base.Serializer.Converters.ToArray <JsonConverter>();
                }
                jTokens.WriteTo(jsonWriter, array);
            }
            else if (valueContract is JsonISerializableContract)
            {
                this.SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
        }
 private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
   contract.InvokeOnSerializing(values.UnderlyingDictionary, this.Serializer.Context);
   this._serializeStack.Add(values.UnderlyingDictionary);
   this.WriteObjectStart(writer, values.UnderlyingDictionary, (JsonContract) contract, member, collectionContract, containerProperty);
   if (contract.ItemContract == null)
     contract.ItemContract = this.Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof (object));
   int top = writer.Top;
   foreach (DictionaryEntry entry in (IDictionary) values)
   {
     string propertyName = this.GetPropertyName(entry);
     string name = contract.PropertyNameResolver != null ? contract.PropertyNameResolver(propertyName) : propertyName;
     try
     {
       object obj = entry.Value;
       JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(obj);
       if (this.ShouldWriteReference(obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
       {
         writer.WritePropertyName(name);
         this.WriteReference(writer, obj);
       }
       else if (this.CheckForCircularReference(writer, obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
       {
         writer.WritePropertyName(name);
         this.SerializeValue(writer, obj, jsonContract, (JsonProperty) null, (JsonContainerContract) contract, member);
       }
     }
     catch (Exception ex)
     {
       if (this.IsErrorHandled(values.UnderlyingDictionary, (JsonContract) contract, (object) name, writer.ContainerPath, ex))
         this.HandleError(writer, top);
       else
         throw;
     }
   }
   writer.WriteEndObject();
   this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
   contract.InvokeOnSerialized(values.UnderlyingDictionary, this.Serializer.Context);
 }
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, base.Serializer.Context);
            SerializeStack.Add(values.UnderlyingDictionary);
            writer.WriteStartObject();
            bool?isReference = contract.IsReference;

            if ((!isReference.HasValue) ? HasFlag(base.Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects) : isReference.Value)
            {
                writer.WritePropertyName("$id");
                writer.WriteValue(base.Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
            }
            if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
            {
                WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
            }
            JsonContract          collectionValueContract2 = base.Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            int                   top        = writer.Top;
            IDictionaryEnumerator enumerator = values.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    DictionaryEntry entry        = (DictionaryEntry)enumerator.Current;
                    string          propertyName = GetPropertyName(entry);
                    propertyName = ((contract.PropertyNameResolver == null) ? propertyName : contract.PropertyNameResolver(propertyName));
                    try
                    {
                        object       value        = entry.Value;
                        JsonContract contractSafe = GetContractSafe(value);
                        if (ShouldWriteReference(value, null, contractSafe))
                        {
                            writer.WritePropertyName(propertyName);
                            WriteReference(writer, value);
                        }
                        else if (CheckForCircularReference(value, null, contract))
                        {
                            writer.WritePropertyName(propertyName);
                            SerializeValue(writer, value, contractSafe, null, collectionValueContract2);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
                        {
                            throw;
                        }
                        HandleError(writer, top);
                    }
                }
            }
            finally
            {
                (enumerator as IDisposable)?.Dispose();
            }
            writer.WriteEndObject();
            SerializeStack.RemoveAt(SerializeStack.Count - 1);
            contract.InvokeOnSerialized(values.UnderlyingDictionary, base.Serializer.Context);
        }
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
        {
            JsonConverter converter = (member != null) ? member.Converter : null;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if ((converter != null ||
                 ((converter = valueContract.Converter) != null) ||
                 ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null) ||
                 ((converter = valueContract.InternalConverter) != null)) &&
                converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract);
            }
            else if (valueContract is JsonPrimitiveContract)
            {
                writer.WriteValue(value);
            }
            else if (valueContract is JsonStringContract)
            {
                SerializeString(writer, value, (JsonStringContract)valueContract);
            }
            else if (valueContract is JsonObjectContract)
            {
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
            }
            else if (valueContract is JsonDictionaryContract)
            {
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
            }
            else if (valueContract is JsonArrayContract)
            {
                if (value is IList)
                {
                    SerializeList(writer, (IList)value, (JsonArrayContract)valueContract, member, collectionValueContract);
                }
                else if (value is IEnumerable)
                {
                    SerializeList(writer, ((IEnumerable)value).Cast <object>().ToList(), (JsonArrayContract)valueContract, member, collectionValueContract);
                }
                else
                {
                    throw new Exception(
                              "Cannot serialize '{0}' into a JSON array. Type does not implement IEnumerable.".FormatWith(
                                  CultureInfo.InvariantCulture, value.GetType()));
                }
            }
            else if (valueContract is JsonLinqContract)
            {
                ((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
            }
#if !SILVERLIGHT && !PocketPC
            else if (valueContract is JsonISerializableContract)
            {
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
            }
#endif
        }
    private object PopulateDictionary(IWrappedDictionary wrappedDictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id)
    {
      object dictionary = wrappedDictionary.UnderlyingDictionary;

      if (id != null)
        AddReference(reader, id, dictionary);

      OnDeserializing(reader, contract, dictionary);

      int initialDepth = reader.Depth;

      if (contract.KeyContract == null)
        contract.KeyContract = GetContractSafe(contract.DictionaryKeyType);

      if (contract.ItemContract == null)
        contract.ItemContract = GetContractSafe(contract.DictionaryValueType);

      JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty);

      bool finished = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            object keyValue = reader.Value;
            try
            {
              try
              {
                keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType);
              }
              catch (Exception ex)
              {
                throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
              }

              if (!ReadForType(reader, contract.ItemContract, dictionaryValueConverter != null))
                throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");

              object itemValue;
              if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead)
                itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null);
              else
                itemValue = CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null);

              wrappedDictionary[keyValue] = itemValue;
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(dictionary, contract, keyValue, reader as IJsonLineInfo, reader.Path, ex))
                HandleError(reader, true, initialDepth);
              else
                throw;
            }
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            finished = true;
            break;
          default:
            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!finished && reader.Read());

      if (!finished)
        ThrowUnexpectedEndException(reader, contract, dictionary, "Unexpected end when deserializing object.");

      OnDeserialized(reader, contract, dictionary);
      return dictionary;
    }
    private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
    {
      object dictionary;

      if (contract.DefaultCreator != null &&
        (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
        dictionary = contract.DefaultCreator();
      else
        throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

      IWrappedDictionary dictionaryWrapper = contract.CreateWrapper(dictionary);

      PopulateDictionary(dictionaryWrapper, reader, contract, id);

      return dictionaryWrapper.UnderlyingDictionary;
    }
Exemple #43
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            object      converter;
            IDictionary dictionaries;

            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            if (member != null)
            {
                converter = member.Converter;
            }
            else
            {
                converter = null;
            }
            if (converter == null)
            {
                if (containerProperty != null)
                {
                    converter = containerProperty.ItemConverter;
                }
                else
                {
                    converter = null;
                }
                if (converter == null)
                {
                    if (containerContract != null)
                    {
                        converter = containerContract.ItemConverter;
                    }
                    else
                    {
                        converter = null;
                    }
                    if (converter == null)
                    {
                        converter = valueContract.Converter ?? (this.Serializer.GetMatchingConverter(valueContract.UnderlyingType) ?? valueContract.InternalConverter);
                    }
                }
            }
            JsonConverter jsonConverter = (JsonConverter)converter;

            if (jsonConverter != null && jsonConverter.CanWrite)
            {
                this.SerializeConvertable(writer, jsonConverter, value, valueContract, containerContract, containerProperty);
                return;
            }
            switch (valueContract.ContractType)
            {
            case JsonContractType.Object:
            {
                this.SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Array:
            {
                JsonArrayContract jsonArrayContract = (JsonArrayContract)valueContract;
                if (!jsonArrayContract.IsMultidimensionalArray)
                {
                    this.SerializeList(writer, (IEnumerable)value, jsonArrayContract, member, containerContract, containerProperty);
                    return;
                }
                this.SerializeMultidimensionalArray(writer, (Array)value, jsonArrayContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Primitive:
            {
                this.SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.String:
            {
                this.SerializeString(writer, value, (JsonStringContract)valueContract);
                return;
            }

            case JsonContractType.Dictionary:
            {
                JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)valueContract;
                JsonWriter             jsonWriter             = writer;
                if (value is IDictionary)
                {
                    dictionaries = (IDictionary)value;
                }
                else
                {
                    dictionaries = jsonDictionaryContract.CreateWrapper(value);
                }
                this.SerializeDictionary(jsonWriter, dictionaries, jsonDictionaryContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Dynamic:
            {
                return;
            }

            case JsonContractType.Serializable:
            {
                this.SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Linq:
            {
                ((JToken)value).WriteTo(writer, this.Serializer.Converters.ToArray <JsonConverter>());
                return;
            }

            default:
            {
                return;
            }
            }
        }
 // Token: 0x06000C0A RID: 3082
 // RVA: 0x000479FC File Offset: 0x00045BFC
 private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
     IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
     object obj = (wrappedDictionary != null) ? wrappedDictionary.UnderlyingDictionary : values;
     this.OnSerializing(writer, contract, obj);
     this._serializeStack.Add(obj);
     this.WriteObjectStart(writer, obj, contract, member, collectionContract, containerProperty);
     if (contract.ItemContract == null)
     {
         contract.ItemContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
     }
     if (contract.KeyContract == null)
     {
         contract.KeyContract = this.Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
     }
     int top = writer.Top;
     foreach (DictionaryEntry dictionaryEntry in values)
     {
         bool escape;
         string text = this.GetPropertyName(writer, dictionaryEntry.Key, contract.KeyContract, out escape);
         text = ((contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(text) : text);
         try
         {
             object value = dictionaryEntry.Value;
             JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(value);
             if (this.ShouldWriteReference(value, null, jsonContract, contract, member))
             {
                 writer.WritePropertyName(text, escape);
                 this.WriteReference(writer, value);
             }
             else if (this.CheckForCircularReference(writer, value, null, jsonContract, contract, member))
             {
                 writer.WritePropertyName(text, escape);
                 this.SerializeValue(writer, value, jsonContract, null, contract, member);
             }
         }
         catch (Exception ex)
         {
             if (!base.IsErrorHandled(obj, contract, text, null, writer.ContainerPath, ex))
             {
                 throw;
             }
             this.HandleError(writer, top);
         }
     }
     writer.WriteEndObject();
     this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
     this.OnSerialized(writer, contract, obj);
 }
		private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
		{
			contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

			SerializeStack.Add(values.UnderlyingDictionary);
			writer.WriteStartObject();

			bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
			if (isReference)
			{
				writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
				writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
			}
			if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
			{
				WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
			}

			JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

			int initialDepth = writer.Top;

			// Mono Unity 3.0 fix
			IDictionary d = values;
//#if !(UNITY_IPHONE || UNITY_IOS)
			foreach (DictionaryEntry entry in d)
			{
				string propertyName = GetPropertyName(entry);

				propertyName = (contract.PropertyNameResolver != null)
								 ? contract.PropertyNameResolver(propertyName)
								 : propertyName;
				try
				{
					object value = entry.Value;
					JsonContract valueContract = GetContractSafe(value);

					if (ShouldWriteReference(value, null, valueContract))
					{
						writer.WritePropertyName(propertyName);
						WriteReference(writer, value);
					}
					else
					{
						if (!CheckForCircularReference(value, null, contract))
							continue;

						writer.WritePropertyName(propertyName);

						SerializeValue(writer, value, valueContract, null, childValuesContract);
					}
				}
				catch (Exception ex)
				{
					if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
						HandleError(writer, initialDepth);
					else
						throw;
				}
			}
//#else
//			string propertyName;

//			d.ForEach(originalEntry =>
//			{
//				var entry = (DictionaryEntry)originalEntry;

//				propertyName = GetPropertyName(entry);

//				propertyName = (contract.PropertyNameResolver != null)
//								 ? contract.PropertyNameResolver(propertyName)
//								 : propertyName;

//				try
//				{
//					object value = entry.Value;
//					JsonContract valueContract = GetContractSafe(value);

//					if (ShouldWriteReference(value, null, valueContract))
//					{
//						writer.WritePropertyName(propertyName);
//						WriteReference(writer, value);
//					}
//					else
//					{
//						if (!CheckForCircularReference(value, null, contract))
//							return;

//						writer.WritePropertyName(propertyName);

//						SerializeValue(writer, value, valueContract, null, childValuesContract);
//					}
//				}
//				catch (Exception ex)
//				{
//					if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
//						HandleError(writer, initialDepth);
//					else
//						throw;
//				}
//			});


//#endif
			

			writer.WriteEndObject();
			SerializeStack.RemoveAt(SerializeStack.Count - 1);

			contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
		}
 // Token: 0x06000BD1 RID: 3025
 // RVA: 0x00044E70 File Offset: 0x00043070
 private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id)
 {
     IWrappedDictionary wrappedDictionary = dictionary as IWrappedDictionary;
     object obj = (wrappedDictionary != null) ? wrappedDictionary.UnderlyingDictionary : dictionary;
     if (id != null)
     {
         this.AddReference(reader, id, obj);
     }
     this.OnDeserializing(reader, contract, obj);
     int depth = reader.Depth;
     if (contract.KeyContract == null)
     {
         contract.KeyContract = this.GetContractSafe(contract.DictionaryKeyType);
     }
     if (contract.ItemContract == null)
     {
         contract.ItemContract = this.GetContractSafe(contract.DictionaryValueType);
     }
     JsonConverter jsonConverter = contract.ItemConverter ?? this.GetConverter(contract.ItemContract, null, contract, containerProperty);
     PrimitiveTypeCode primitiveTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract)contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty;
     bool flag = false;
     while (true)
     {
         JsonToken tokenType = reader.TokenType;
         switch (tokenType)
         {
         case JsonToken.PropertyName:
         {
             object obj2 = reader.Value;
             if (!this.CheckPropertyName(reader, obj2.ToString()))
             {
                 try
                 {
                     try
                     {
                         DateParseHandling dateParseHandling;
                         switch (primitiveTypeCode)
                         {
                         case PrimitiveTypeCode.DateTime:
                         case PrimitiveTypeCode.DateTimeNullable:
                             dateParseHandling = DateParseHandling.DateTime;
                             break;
                         default:
                             dateParseHandling = DateParseHandling.None;
                             break;
                         }
                         object obj3;
                         if (dateParseHandling != DateParseHandling.None && DateTimeUtils.TryParseDateTime(obj2.ToString(), dateParseHandling, reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out obj3))
                         {
                             obj2 = obj3;
                         }
                         else
                         {
                             obj2 = this.EnsureType(reader, obj2, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType);
                         }
                     }
                     catch (Exception ex)
                     {
                         throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.", CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
                     }
                     if (!this.ReadForType(reader, contract.ItemContract, jsonConverter != null))
                     {
                         throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
                     }
                     object value;
                     if (jsonConverter != null && jsonConverter.CanRead)
                     {
                         value = this.DeserializeConvertable(jsonConverter, reader, contract.DictionaryValueType, null);
                     }
                     else
                     {
                         value = this.CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null);
                     }
                     dictionary[obj2] = value;
                     break;
                 }
                 catch (Exception ex2)
                 {
                     if (!base.IsErrorHandled(obj, contract, obj2, reader as IJsonLineInfo, reader.Path, ex2))
                     {
                         throw;
                     }
                     this.HandleError(reader, true, depth);
                     break;
                 }
                 goto IL_20B;
             }
             break;
         }
         case JsonToken.Comment:
             break;
         default:
             goto IL_20B;
         }
         IL_216:
         if (flag)
         {
             break;
         }
         if (!reader.Read())
         {
             break;
         }
         continue;
         IL_20B:
         if (tokenType != JsonToken.EndObject)
         {
             goto Block_10;
         }
         flag = true;
         goto IL_216;
     }
     goto IL_23B;
     Block_10:
     throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
     IL_23B:
     if (!flag)
     {
         this.ThrowUnexpectedEndException(reader, contract, obj, "Unexpected end when deserializing object.");
     }
     this.OnDeserialized(reader, contract, obj);
     return obj;
 }
 protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
 {
   JsonDictionaryContract dictionaryContract = new JsonDictionaryContract(objectType);
   this.InitializeContract((JsonContract) dictionaryContract);
   dictionaryContract.PropertyNameResolver = new Func<string, string>(this.ResolvePropertyName);
   return dictionaryContract;
 }
Exemple #48
0
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

            _serializeStack.Add(values.UnderlyingDictionary);

            WriteObjectStart(writer, values.UnderlyingDictionary, contract, member, collectionContract, collectionValueContract);

            if (contract.DictionaryValueContract == null)
            {
                contract.DictionaryValueContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            JsonContract dictionaryValueContract = (contract.DictionaryValueContract.UnderlyingType.IsSealed()) ? contract.DictionaryValueContract : null;

            int initialDepth = writer.Top;

            // Mono Unity 3.0 fix
            IWrappedDictionary d = values;

            foreach (DictionaryEntry entry in d)
            {
                string propertyName = GetPropertyName(entry);

                propertyName = (contract.PropertyNameResolver != null)
                         ? contract.PropertyNameResolver(propertyName)
                         : propertyName;

                try
                {
                    object       value         = entry.Value;
                    JsonContract valueContract = dictionaryValueContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract))
                    {
                        writer.WritePropertyName(propertyName);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(value, null, valueContract, contract))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName);

                        SerializeValue(writer, value, valueContract, null, contract, dictionaryValueContract);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
        }
Exemple #49
0
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            JsonConverter converter =
                ((member != null) ? member.Converter : null) ??
                ((containerProperty != null) ? containerProperty.ItemConverter : null) ??
                ((containerContract != null) ? containerContract.ItemConverter : null) ??
                valueContract.Converter ??
                Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
                valueContract.InternalConverter;

            if (converter != null && converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
                return;
            }

            switch (valueContract.ContractType)
            {
            case JsonContractType.Object:
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
                break;

            case JsonContractType.Array:
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                if (!arrayContract.IsMultidimensionalArray)
                {
                    SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
                }
                else
                {
                    SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
                }
                break;

            case JsonContractType.Primitive:
                SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
                break;

            case JsonContractType.String:
                SerializeString(writer, value, (JsonStringContract)valueContract);
                break;

            case JsonContractType.Dictionary:
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
                break;

#if !(NET35 || NET20 || PORTABLE40)
            case JsonContractType.Dynamic:
                SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
                break;
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
            case JsonContractType.Serializable:
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
                break;
#endif
            case JsonContractType.Linq:
                ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
                break;
            }
        }
Exemple #50
0
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
            IDictionaryEnumerator e = values.GetEnumerator();

            try
            {
                while (e.MoveNext())
                {
                    DictionaryEntry entry = e.Entry;

                    string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);

                    propertyName = (contract.DictionaryKeyResolver != null)
                        ? contract.DictionaryKeyResolver(propertyName)
                        : propertyName;

                    try
                    {
                        object       value         = entry.Value;
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, escape);
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                continue;
                            }

                            writer.WritePropertyName(propertyName, escape);

                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            finally
            {
                (e as IDisposable)?.Dispose();
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
Exemple #51
0
        private object PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, string id)
        {
            if (id != null)
            {
                Serializer.ReferenceResolver.AddReference(id, dictionary.UnderlyingDictionary);
            }

            contract.InvokeOnDeserializing(dictionary.UnderlyingDictionary, Serializer.Context);

            int initialDepth = reader.Depth;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    object keyValue;
                    try
                    {
                        keyValue = EnsureType(reader.Value, contract.DictionaryKeyType);
                    }
                    catch (Exception ex)
                    {
                        throw new JsonSerializationException("Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
                    }

                    if (!ReadForType(reader, contract.DictionaryValueType, null))
                    {
                        throw new JsonSerializationException("Unexpected end when deserializing object.");
                    }

                    try
                    {
                        dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, GetContractSafe(contract.DictionaryValueType));
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(dictionary, contract, keyValue, ex))
                        {
                            HandleError(reader, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    break;

                case JsonToken.EndObject:
                    contract.InvokeOnDeserialized(dictionary.UnderlyingDictionary, Serializer.Context);

                    return(dictionary.UnderlyingDictionary);

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (reader.Read());

            throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
        private object CreateAndPopulateDictionary(JsonReader reader, JsonDictionaryContract contract, string id)
        {
            IWrappedDictionary dictionary = contract.CreateWrapper(contract.DefaultContstructor.Invoke(null));

              PopulateDictionary(dictionary, reader, contract, id);

              return dictionary.UnderlyingDictionary;
        }
        private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultConstructor)
        {
            if (contract.IsReadOnlyOrFixedSize)
              {
            createdFromNonDefaultConstructor = true;
            return contract.CreateTemporaryDictionary();
              }
              else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
              {
            object dictionary = contract.DefaultCreator();

            if (contract.ShouldCreateWrapper)
              dictionary = contract.CreateWrapper(dictionary);

            createdFromNonDefaultConstructor = false;
            return (IDictionary) dictionary;
              }
              else if (contract.ParametrizedConstructor != null)
              {
            createdFromNonDefaultConstructor = true;
            return contract.CreateTemporaryDictionary();
              }
              else
              {
            throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
              }
        }
        private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator)
        {
            if (contract.OverrideCreator != null)
            {
                if (contract.HasParameterizedCreator)
                {
                    createdFromNonDefaultCreator = true;
                    return contract.CreateTemporaryDictionary();
                }
                else
                {
                    createdFromNonDefaultCreator = false;
                    return (IDictionary)contract.OverrideCreator();
                }
            }
            else if (contract.IsReadOnlyOrFixedSize)
            {
                createdFromNonDefaultCreator = true;
                return contract.CreateTemporaryDictionary();
            }
            else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
            {
                object dictionary = contract.DefaultCreator();

                if (contract.ShouldCreateWrapper)
                {
                    dictionary = contract.CreateWrapper(dictionary);
                }

                createdFromNonDefaultCreator = false;
                return (IDictionary)dictionary;
            }
            else if (contract.HasParameterizedCreatorInternal)
            {
                createdFromNonDefaultCreator = true;
                return contract.CreateTemporaryDictionary();
            }
            else
            {
                if (!contract.IsInstantiable)
                {
                    throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
                }

                throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
            }
        }
    private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

      _serializeStack.Add(values.UnderlyingDictionary);

      WriteObjectStart(writer, values.UnderlyingDictionary, contract, member, collectionContract, containerProperty);

      if (contract.ItemContract == null)
        contract.ItemContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

      int initialDepth = writer.Top;

      // Mono Unity 3.0 fix
      IWrappedDictionary d = values;

      foreach (DictionaryEntry entry in d)
      {
        string propertyName = GetPropertyName(entry);

        propertyName = (contract.PropertyNameResolver != null)
                         ? contract.PropertyNameResolver(propertyName)
                         : propertyName;

        try
        {
          object value = entry.Value;
          JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

          if (ShouldWriteReference(value, null, valueContract, contract, member))
          {
            writer.WritePropertyName(propertyName);
            WriteReference(writer, value);
          }
          else
          {
            if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
              continue;

            writer.WritePropertyName(propertyName);

            SerializeValue(writer, value, valueContract, null, contract, member);
          }
        }
        catch (Exception ex)
        {
          if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, writer.ContainerPath, ex))
            HandleError(writer, initialDepth);
          else
            throw;
        }
      }

      writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);

      contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
    }
    private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract)
    {
      contract.InvokeOnSerializing(values);

      SerializeStack.Add(values);
      writer.WriteStartObject();

      bool isReference = contract.IsReference ?? HasFlag(_serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
      if (isReference)
      {
        writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
        writer.WriteValue(_serializer.ReferenceResolver.GetReference(values));
      }
      if (HasFlag(_serializer.TypeNameHandling, TypeNameHandling.Objects))
      {
        WriteTypeProperty(writer, values.GetType());
      }

      foreach (DictionaryEntry entry in values)
      {
        string propertyName = entry.Key.ToString();
        object value = entry.Value;

        if (ShouldWriteReference(value, null))
        {
          writer.WritePropertyName(propertyName);
          WriteReference(writer, value);
        }
        else
        {
          if (!CheckForCircularReference(value, null))
            continue;

          writer.WritePropertyName(propertyName);
          SerializeValue(writer, value, null);
        }
      }

      writer.WriteEndObject();
      SerializeStack.RemoveAt(SerializeStack.Count - 1);

      contract.InvokeOnSerialized(values);
    }
    private object PopulateDictionary(IWrappedDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, string id)
    {
      if (id != null)
        Serializer.ReferenceResolver.AddReference(this, id, dictionary.UnderlyingDictionary);

      contract.InvokeOnDeserializing(dictionary.UnderlyingDictionary, Serializer.Context);

      int initialDepth = reader.Depth;

      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            object keyValue = reader.Value;
            try
            {
              if (contract.DictionaryKeyContract == null)
                contract.DictionaryKeyContract = GetContractSafe(contract.DictionaryKeyType);
              
              try
              {
                keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.DictionaryKeyContract, contract.DictionaryKeyType);
              }
              catch (Exception ex)
              {
                throw CreateSerializationException(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
              }

              if (contract.DictionaryValueContract == null)
                contract.DictionaryValueContract = GetContractSafe(contract.DictionaryValueType);

              JsonConverter dictionaryValueConverter = GetConverter(contract.DictionaryValueContract, null);

              if (!ReadForType(reader, contract.DictionaryValueContract, dictionaryValueConverter != null, false))
                throw CreateSerializationException(reader, "Unexpected end when deserializing object.");

              dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, contract.DictionaryValueContract, dictionaryValueConverter);
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(dictionary, contract, keyValue, reader.Path, ex))
                HandleError(reader, initialDepth);
              else
                throw;
            }
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            contract.InvokeOnDeserialized(dictionary.UnderlyingDictionary, Serializer.Context);

            return dictionary.UnderlyingDictionary;
          default:
            throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (reader.Read());

      throw CreateSerializationException(reader, "Unexpected end when deserializing object.");
    }
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            JsonConverter jsonConverter;

            if (((jsonConverter = ((member != null) ? member.Converter : null)) != null || (jsonConverter = ((containerProperty != null) ? containerProperty.ItemConverter : null)) != null || (jsonConverter = ((containerContract != null) ? containerContract.ItemConverter : null)) != null || (jsonConverter = valueContract.Converter) != null || (jsonConverter = this.Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null || (jsonConverter = valueContract.InternalConverter) != null) && jsonConverter.CanWrite)
            {
                this.SerializeConvertable(writer, jsonConverter, value, valueContract, containerContract, containerProperty);
                return;
            }
            switch (valueContract.ContractType)
            {
            case JsonContractType.Object:
                this.SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
                return;

            case JsonContractType.Array:
            {
                JsonArrayContract jsonArrayContract = (JsonArrayContract)valueContract;
                if (!jsonArrayContract.IsMultidimensionalArray)
                {
                    this.SerializeList(writer, (IEnumerable)value, jsonArrayContract, member, containerContract, containerProperty);
                    return;
                }
                this.SerializeMultidimensionalArray(writer, (Array)value, jsonArrayContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Primitive:
                this.SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
                return;

            case JsonContractType.String:
                this.SerializeString(writer, value, (JsonStringContract)valueContract);
                return;

            case JsonContractType.Dictionary:
            {
                JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)valueContract;
                this.SerializeDictionary(writer, (value is IDictionary) ? ((IDictionary)value) : jsonDictionaryContract.CreateWrapper(value), jsonDictionaryContract, member, containerContract, containerProperty);
                return;
            }

            case JsonContractType.Dynamic:
                this.SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
                return;

            case JsonContractType.Serializable:
                this.SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
                return;

            case JsonContractType.Linq:
                ((JToken)value).WriteTo(writer, this.Serializer.Converters.ToArray <JsonConverter>());
                return;

            default:
                return;
            }
        }