Contract details for a Type used by the JsonSerializer.
Inheritance: JsonContract
Example #1
0
 private Schema CreateArraySchema(JsonArrayContract arrayContract)
 {
     var itemType = arrayContract.CollectionItemType ?? typeof(object);
     return new Schema
         {
             Type = "array",
             Items = CreateSchema(itemType, true)
         };
 }
 private void SerializeEnumerable(JsonWriter writer, IEnumerable values, JsonArrayContract contract)
 {
     SerializeList(writer, values.Cast<object>().ToList(), contract);
 }
    private void SerializeList(JsonWriter writer, IList values, JsonArrayContract contract)
    {
      contract.InvokeOnSerializing(values);

      SerializeStack.Add(values);

      bool isReference = contract.IsReference ?? HasFlag(_serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
      bool includeTypeDetails = HasFlag(_serializer.TypeNameHandling, TypeNameHandling.Arrays);

      if (isReference || includeTypeDetails)
      {
        writer.WriteStartObject();

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

      writer.WriteStartArray();

      for (int i = 0; i < values.Count; i++)
      {
        object value = values[i];

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

          SerializeValue(writer, value, null);
        }
      }

      writer.WriteEndArray();

      if (isReference)
      {
        writer.WriteEndObject();
      }

      SerializeStack.RemoveAt(SerializeStack.Count - 1);

      contract.InvokeOnSerialized(values);
    }
		private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract)
		{
			return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) =>
			{
				if (reference != null && isTemporaryListReference)
					throw new JsonSerializationException("Cannot preserve reference to array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
				if (contract.OnSerializing != null && isTemporaryListReference)
					throw new JsonSerializationException("Cannot call OnSerializing on an array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
				if (contract.OnError != null && isTemporaryListReference)
					throw new JsonSerializationException("Cannot call OnError on an array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

				if (!contract.IsMultidimensionalArray)
					PopulateList(contract.CreateWrapper(l), reader, reference, contract);
				else
					PopulateMultidimensionalArray(l, reader, reference, contract);
			});
		}
 private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
 {
   object underlyingCollection = wrappedList.UnderlyingCollection;
   if (id != null)
     this.AddReference(reader, id, underlyingCollection);
   if (wrappedList.IsFixedSize)
   {
     reader.Skip();
     return underlyingCollection;
   }
   else
   {
     contract.InvokeOnDeserializing(underlyingCollection, this.Serializer.Context);
     int depth = reader.Depth;
     JsonContract contractSafe = this.GetContractSafe(contract.CollectionItemType);
     JsonConverter converter = this.GetConverter(contractSafe, (JsonConverter) null, (JsonContainerContract) contract, containerProperty);
     int? nullable1 = new int?();
     bool flag = false;
     do
     {
       try
       {
         if (this.ReadForType(reader, contractSafe, converter != null))
         {
           switch (reader.TokenType)
           {
             case JsonToken.Comment:
               break;
             case JsonToken.EndArray:
               flag = true;
               break;
             default:
               object obj = converter == null || !converter.CanRead ? this.CreateValueInternal(reader, contract.CollectionItemType, contractSafe, (JsonProperty) null, (JsonContainerContract) contract, containerProperty, (object) null) : converter.ReadJson(reader, contract.CollectionItemType, (object) null, (JsonSerializer) this.GetInternalSerializer());
               wrappedList.Add(obj);
               break;
           }
         }
         else
           break;
       }
       catch (Exception ex)
       {
         JsonPosition position = reader.GetPosition(depth);
         if (this.IsErrorHandled(underlyingCollection, (JsonContract) contract, (object) position.Position, reader.Path, ex))
         {
           this.HandleError(reader, true, depth);
           if (nullable1.HasValue)
           {
             int? nullable2 = nullable1;
             int? nullable3 = position.Position;
             if ((nullable2.GetValueOrDefault() != nullable3.GetValueOrDefault() ? 0 : (nullable2.HasValue == nullable3.HasValue ? 1 : 0)) != 0)
               throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
           }
           nullable1 = position.Position;
         }
         else
           throw;
       }
     }
     while (!flag);
     if (!flag)
       this.ThrowUnexpectedEndException(reader, (JsonContract) contract, underlyingCollection, "Unexpected end when deserializing array.");
     contract.InvokeOnDeserialized(underlyingCollection, this.Serializer.Context);
     return underlyingCollection;
   }
 }
    private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
    {
      int dimension = indices.Length;
      int[] newIndices = new int[dimension + 1];
      for (int i = 0; i < dimension; i++)
      {
        newIndices[i] = indices[i];
      }

      writer.WriteStartArray();

      for (int i = 0; i < values.GetLength(dimension); i++)
      {
        newIndices[dimension] = i;
        bool isTopLevel = (newIndices.Length == values.Rank);

        if (isTopLevel)
        {
          object value = values.GetValue(newIndices);

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

            if (ShouldWriteReference(value, null, valueContract, contract, member))
            {
              WriteReference(writer, value);
            }
            else
            {
              if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
              {
                SerializeValue(writer, value, valueContract, null, contract, member);
              }
            }
          }
          catch (Exception ex)
          {
            if (IsErrorHandled(values, contract, i, writer.ContainerPath, ex))
              HandleError(writer, initialDepth + 1);
            else
              throw;
          }
        }
        else
        {
          SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
        }
      }

      writer.WriteEndArray();
    }
Example #7
0
        private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, string reference, JsonArrayContract contract)
        {
            object underlyingCollection = wrappedList.UnderlyingCollection;

            if (wrappedList.IsFixedSize)
            {
                reader.Skip();
                return(wrappedList.UnderlyingCollection);
            }
            if (reference != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, reference, underlyingCollection);
            }
            contract.InvokeOnDeserializing(underlyingCollection, base.Serializer.Context);
            int depth = reader.Depth;

            while (ReadForTypeArrayHack(reader, contract.CollectionItemType))
            {
                switch (reader.TokenType)
                {
                case JsonToken.EndArray:
                    contract.InvokeOnDeserialized(underlyingCollection, base.Serializer.Context);
                    return(wrappedList.UnderlyingCollection);

                case JsonToken.Comment:
                    continue;
                }
                try
                {
                    object value = CreateValueNonProperty(reader, contract.CollectionItemType, GetContractSafe(contract.CollectionItemType));
                    wrappedList.Add(value);
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingCollection, contract, wrappedList.Count, ex))
                    {
                        HandleError(reader, depth);
                        continue;
                    }
                    throw;
                }
            }
            throw new JsonSerializationException("Unexpected end when deserializing array.");
        }
        private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
        {
            int rank = contract.UnderlyingType.GetArrayRank();

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

              OnDeserializing(reader, contract, list);

              JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
              JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);

              int? previousErrorIndex = null;
              Stack<IList> listStack = new Stack<IList>();
              listStack.Push(list);
              IList currentList = list;

              bool finished = false;
              do
              {
            int initialDepth = reader.Depth;

            if (listStack.Count == rank)
            {
              try
              {
            if (ReadForType(reader, collectionItemContract, collectionItemConverter != null))
            {
              switch (reader.TokenType)
              {
                case JsonToken.EndArray:
                  listStack.Pop();
                  currentList = listStack.Peek();
                  previousErrorIndex = null;
                  break;
                case JsonToken.Comment:
                  break;
                default:
                  object value;

                  if (collectionItemConverter != null && collectionItemConverter.CanRead)
                    value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
                  else
                    value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null);

                  currentList.Add(value);
                  break;
              }
            }
            else
            {
              break;
            }
              }
              catch (Exception ex)
              {
            JsonPosition errorPosition = reader.GetPosition(initialDepth);

            if (IsErrorHandled(list, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex))
            {
              HandleError(reader, true, initialDepth);

              if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
              {
                // reader index has not moved since previous error handling
                // break out of reading array to prevent infinite loop
                throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
              }
              else
              {
                previousErrorIndex = errorPosition.Position;
              }
            }
            else
            {
              throw;
            }
              }
            }
            else
            {
              if (reader.Read())
              {
            switch (reader.TokenType)
            {
              case JsonToken.StartArray:
                IList newList = new List<object>();
                currentList.Add(newList);
                listStack.Push(newList);
                currentList = newList;
                break;
              case JsonToken.EndArray:
                listStack.Pop();

                if (listStack.Count > 0)
                {
                  currentList = listStack.Peek();
                }
                else
                {
                  finished = true;
                }
                break;
              case JsonToken.Comment:
                break;
              default:
                throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + reader.TokenType);
            }
              }
              else
              {
            break;
              }
            }
              } while (!finished);

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

              OnDeserialized(reader, contract, list);
              return list;
        }
 private void SerializeEnumerable(JsonWriter writer, IEnumerable values, JsonArrayContract contract)
 {
     SerializeList(writer, values.Cast <object>().ToList(), contract);
 }
        private void SerializeList(JsonWriter writer, IList values, JsonArrayContract contract)
        {
            contract.InvokeOnSerializing(values);

            SerializeStack.Add(values);

            bool isReference        = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
            bool includeTypeDetails = HasFlag(Serializer.TypeNameHandling, TypeNameHandling.Arrays);

            if (isReference || includeTypeDetails)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                    writer.WriteValue(Serializer.ReferenceResolver.GetReference(values));
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
            }

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            for (int i = 0; i < values.Count; i++)
            {
                try
                {
                    object value = values[i];

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

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

            writer.WriteEndArray();

            if (isReference)
            {
                writer.WriteEndObject();
            }

            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values);
        }
        private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id)
        {
            ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");
            Type underlyingType = contract.UnderlyingType;
            IDictionary <JsonProperty, object>  dictionary  = ResolvePropertyAndConstructorValues(contract, reader, underlyingType);
            IDictionary <ParameterInfo, object> dictionary2 = ((IEnumerable <ParameterInfo>)constructorInfo.GetParameters()).ToDictionary((Func <ParameterInfo, ParameterInfo>)((ParameterInfo p) => p), (Func <ParameterInfo, object>)((ParameterInfo p) => null));
            IDictionary <JsonProperty, object>  dictionary3 = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> item in dictionary)
            {
                ParameterInfo key = dictionary2.ForgivingCaseSensitiveFind((KeyValuePair <ParameterInfo, object> kv) => kv.Key.Name, item.Key.UnderlyingName).Key;
                if (key != null)
                {
                    dictionary2[key] = item.Value;
                }
                else
                {
                    dictionary3.Add(item);
                }
            }
            object obj = constructorInfo.Invoke(dictionary2.Values.ToArray());

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, obj);
            }
            contract.InvokeOnDeserializing(obj, base.Serializer.Context);
            foreach (KeyValuePair <JsonProperty, object> item2 in dictionary3)
            {
                JsonProperty key2  = item2.Key;
                object       value = item2.Value;
                if (ShouldSetPropertyValue(item2.Key, item2.Value))
                {
                    key2.ValueProvider.SetValue(obj, value);
                }
                else if (!key2.Writable && value != null)
                {
                    JsonContract jsonContract = base.Serializer.ContractResolver.ResolveContract(key2.PropertyType);
                    if (jsonContract is JsonArrayContract)
                    {
                        JsonArrayContract jsonArrayContract = jsonContract as JsonArrayContract;
                        object            value2            = key2.ValueProvider.GetValue(obj);
                        if (value2 != null)
                        {
                            IWrappedCollection wrappedCollection  = jsonArrayContract.CreateWrapper(value2);
                            IWrappedCollection wrappedCollection2 = jsonArrayContract.CreateWrapper(value);
                            IEnumerator        enumerator3        = wrappedCollection2.GetEnumerator();
                            try
                            {
                                while (enumerator3.MoveNext())
                                {
                                    object current3 = enumerator3.Current;
                                    wrappedCollection.Add(current3);
                                }
                            }
                            finally
                            {
                                IDisposable disposable;
                                if ((disposable = (enumerator3 as IDisposable)) != null)
                                {
                                    disposable.Dispose();
                                }
                            }
                        }
                    }
                    else if (jsonContract is JsonDictionaryContract)
                    {
                        JsonDictionaryContract jsonDictionaryContract = jsonContract as JsonDictionaryContract;
                        object value3 = key2.ValueProvider.GetValue(obj);
                        if (value3 != null)
                        {
                            IWrappedDictionary    wrappedDictionary  = jsonDictionaryContract.CreateWrapper(value3);
                            IWrappedDictionary    wrappedDictionary2 = jsonDictionaryContract.CreateWrapper(value);
                            IDictionaryEnumerator enumerator4        = wrappedDictionary2.GetEnumerator();
                            try
                            {
                                while (enumerator4.MoveNext())
                                {
                                    DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator4.Current;
                                    wrappedDictionary.Add(dictionaryEntry.Key, dictionaryEntry.Value);
                                }
                            }
                            finally
                            {
                                IDisposable disposable2;
                                if ((disposable2 = (enumerator4 as IDisposable)) != null)
                                {
                                    disposable2.Dispose();
                                }
                            }
                        }
                    }
                }
            }
            contract.InvokeOnDeserialized(obj, base.Serializer.Context);
            return(obj);
        }
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            OnSerializing(writer, contract, values.UnderlyingCollection);

            _serializeStack.Add(values.UnderlyingCollection);

            bool hasWrittenMetadataObject = WriteStartArray(writer, values.UnderlyingCollection, contract, member, collectionContract, containerProperty);

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int    index         = 0;
            object valuePrevious = new object();

            try {
                // note that an error in the IEnumerable won't be caught
                foreach (object value in values)
                {
                    try {
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                SerializeValue(writer, value, valueContract, null, contract, member);
                            }
                        }
                    } catch (Exception ex) {
                        if (IsErrorHandled(values.UnderlyingCollection, contract, index, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    } finally {
                        index++;
                        valuePrevious = value;
                    }
                }
            } catch (Exception e) {
                string msg = "valuePrevious[" + valuePrevious.ToString() + "] trying to catch COLLECTION_CHANGED";
                throw new Exception(msg, e);
            }

            writer.WriteEndArray();

            if (hasWrittenMetadataObject)
            {
                writer.WriteEndObject();
            }

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, values.UnderlyingCollection);
        }
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingCollection, base.Serializer.Context);
            this.SerializeStack.Add(values.UnderlyingCollection);
            bool?isReference = contract.IsReference;
            bool flag        = (!isReference.get_HasValue()) ? this.HasFlag(base.Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays) : isReference.get_Value();
            bool flag2       = this.ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

            if (flag || flag2)
            {
                writer.WriteStartObject();
                if (flag)
                {
                    writer.WritePropertyName("$id");
                    writer.WriteValue(base.Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
                }
                if (flag2)
                {
                    this.WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
                }
                writer.WritePropertyName("$values");
            }
            JsonContract collectionValueContract2 = base.Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));

            writer.WriteStartArray();
            int         top        = writer.Top;
            int         num        = 0;
            IEnumerator enumerator = values.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    object current = enumerator.get_Current();
                    try
                    {
                        JsonContract contractSafe = this.GetContractSafe(current);
                        if (this.ShouldWriteReference(current, null, contractSafe))
                        {
                            this.WriteReference(writer, current);
                        }
                        else if (this.CheckForCircularReference(current, default(ReferenceLoopHandling?), contract))
                        {
                            this.SerializeValue(writer, current, contractSafe, null, collectionValueContract2);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!base.IsErrorHandled(values.UnderlyingCollection, contract, num, ex))
                        {
                            throw;
                        }
                        this.HandleError(writer, top);
                    }
                    finally
                    {
                        num++;
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            writer.WriteEndArray();
            if (flag || flag2)
            {
                writer.WriteEndObject();
            }
            this.SerializeStack.RemoveAt(this.SerializeStack.get_Count() - 1);
            contract.InvokeOnSerialized(values.UnderlyingCollection, base.Serializer.Context);
        }
        private void SerializeList(JsonWriter writer, IList values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values, Serializer.Context);

              SerializeStack.Add(values);

              bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
              bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

              if (isReference || includeTypeDetails)
              {
            writer.WriteStartObject();

            if (isReference)
            {
              writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
              writer.WriteValue(Serializer.ReferenceResolver.GetReference(values));
            }
            if (includeTypeDetails)
            {
              WriteTypeProperty(writer, values.GetType());
            }
            writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
              }

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

              writer.WriteStartArray();

              int initialDepth = writer.Top;

              for (int i = 0; i < values.Count; i++)
              {
            try
            {
              object value = values[i];
              JsonContract valueContract = GetContractSafe(value);

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

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

              writer.WriteEndArray();

              if (isReference || includeTypeDetails)
              {
            writer.WriteEndObject();
              }

              SerializeStack.RemoveAt(SerializeStack.Count - 1);

              contract.InvokeOnSerialized(values, Serializer.Context);
        }
Example #15
0
        private object PopulateMultidimensionalArray(IList list, JsonReader reader, string reference, JsonArrayContract contract)
        {
            int arrayRank = contract.UnderlyingType.GetArrayRank();

            if (reference != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, reference, list);
            }
            contract.InvokeOnDeserializing(list, base.Serializer.Context);
            Stack <IList> stack = new Stack <IList>();

            stack.Push(list);
            IList list2 = list;
            bool  flag  = false;

            do
            {
                int depth = reader.Depth;
                if (stack.Count == arrayRank)
                {
                    if (!ReadForTypeArrayHack(reader, contract.CollectionItemType))
                    {
                        break;
                    }
                    switch (reader.TokenType)
                    {
                    case JsonToken.EndArray:
                        stack.Pop();
                        list2 = stack.Peek();
                        continue;

                    case JsonToken.Comment:
                        continue;
                    }
                    try
                    {
                        object value = CreateValueNonProperty(reader, contract.CollectionItemType, GetContractSafe(contract.CollectionItemType));
                        list2.Add(value);
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(list, contract, list2.Count, ex))
                        {
                            HandleError(reader, depth);
                            continue;
                        }
                        throw;
                    }
                    continue;
                }
                if (!reader.Read())
                {
                    break;
                }
                switch (reader.TokenType)
                {
                case JsonToken.StartArray:
                {
                    IList list3 = new List <object>();
                    list2.Add(list3);
                    stack.Push(list3);
                    list2 = list3;
                    break;
                }

                case JsonToken.EndArray:
                    stack.Pop();
                    if (stack.Count > 0)
                    {
                        list2 = stack.Peek();
                    }
                    else
                    {
                        flag = true;
                    }
                    break;

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing multidimensional array: " + reader.TokenType);

                case JsonToken.Comment:
                    break;
                }
            }while (!flag);
            if (!flag)
            {
                throw new JsonSerializationException("Unexpected end when deserializing array." + reader.TokenType);
            }
            contract.InvokeOnDeserialized(list, base.Serializer.Context);
            return(list);
        }
    private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, string reference, JsonArrayContract contract)
    {
      object list = wrappedList.UnderlyingCollection;

      if (reference != null)
        Serializer.ReferenceResolver.AddReference(reference, list);

      contract.InvokeOnDeserializing(list, Serializer.Context);

      int initialDepth = reader.Depth;

      while (reader.Read())
      {
        switch (reader.TokenType)
        {
          case JsonToken.EndArray:
            contract.InvokeOnDeserialized(list, Serializer.Context);

            return wrappedList.UnderlyingCollection;
          case JsonToken.Comment:
            break;
          default:
            try
            {
              object value = CreateValueNonProperty(reader, contract.CollectionItemType, GetContractSafe(contract.CollectionItemType));

              wrappedList.Add(value);
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(list, contract, wrappedList.Count, ex))
                HandleError(reader, initialDepth);
              else
                throw;
            }
            break;
        }
      }

      throw new JsonSerializationException("Unexpected end when deserializing array.");
    }
Example #17
0
        private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id)
        {
            ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");
            Type underlyingType = contract.UnderlyingType;
            IDictionary <JsonProperty, object>  dictionary  = ResolvePropertyAndConstructorValues(contract, reader, underlyingType);
            IDictionary <ParameterInfo, object> dictionary2 = ((IEnumerable <ParameterInfo>)constructorInfo.GetParameters()).ToDictionary((Func <ParameterInfo, ParameterInfo>)((ParameterInfo p) => p), (Func <ParameterInfo, object>)((ParameterInfo p) => null));
            IDictionary <JsonProperty, object>  dictionary3 = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> item in dictionary)
            {
                ParameterInfo key = dictionary2.ForgivingCaseSensitiveFind((KeyValuePair <ParameterInfo, object> kv) => kv.Key.Name, item.Key.UnderlyingName).Key;
                if (key != null)
                {
                    dictionary2[key] = item.Value;
                }
                else
                {
                    dictionary3.Add(item);
                }
            }
            object obj = constructorInfo.Invoke(dictionary2.Values.ToArray());

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, obj);
            }
            contract.InvokeOnDeserializing(obj, base.Serializer.Context);
            foreach (KeyValuePair <JsonProperty, object> item2 in dictionary3)
            {
                JsonProperty key2  = item2.Key;
                object       value = item2.Value;
                if (ShouldSetPropertyValue(item2.Key, item2.Value))
                {
                    key2.ValueProvider.SetValue(obj, value);
                }
                else
                {
                    if (key2.Writable || value == null)
                    {
                        continue;
                    }
                    JsonContract jsonContract = base.Serializer.ContractResolver.ResolveContract(key2.PropertyType);
                    if (jsonContract is JsonArrayContract)
                    {
                        JsonArrayContract jsonArrayContract = jsonContract as JsonArrayContract;
                        object            value2            = key2.ValueProvider.GetValue(obj);
                        if (value2 == null)
                        {
                            continue;
                        }
                        IWrappedCollection wrappedCollection  = jsonArrayContract.CreateWrapper(value2);
                        IWrappedCollection wrappedCollection2 = jsonArrayContract.CreateWrapper(value);
                        foreach (object item3 in wrappedCollection2)
                        {
                            wrappedCollection.Add(item3);
                        }
                    }
                    else
                    {
                        if (!(jsonContract is JsonDictionaryContract))
                        {
                            continue;
                        }
                        JsonDictionaryContract jsonDictionaryContract = jsonContract as JsonDictionaryContract;
                        object value3 = key2.ValueProvider.GetValue(obj);
                        if (value3 == null)
                        {
                            continue;
                        }
                        IWrappedDictionary wrappedDictionary  = jsonDictionaryContract.CreateWrapper(value3);
                        IWrappedDictionary wrappedDictionary2 = jsonDictionaryContract.CreateWrapper(value);
                        foreach (DictionaryEntry item4 in wrappedDictionary2)
                        {
                            wrappedDictionary.Add(item4.Key, item4.Value);
                        }
                    }
                }
            }
            contract.InvokeOnDeserialized(obj, base.Serializer.Context);
            return(obj);
        }
    private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);

      _serializeStack.Add(values.UnderlyingCollection);

      bool hasWrittenMetadataObject = WriteStartArray(writer, values.UnderlyingCollection, contract, member, collectionContract, containerProperty);

      writer.WriteStartArray();

      int initialDepth = writer.Top;

      int index = 0;
      // note that an error in the IEnumerable won't be caught
      foreach (object value in values)
      {
        try
        {
          JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

          if (ShouldWriteReference(value, null, valueContract, contract, member))
          {
            WriteReference(writer, value);
          }
          else
          {
            if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
            {
              SerializeValue(writer, value, valueContract, null, contract, member);
            }
          }
        }
        catch (Exception ex)
        {
          if (IsErrorHandled(values.UnderlyingCollection, contract, index, writer.ContainerPath, ex))
            HandleError(writer, initialDepth);
          else
            throw;
        }
        finally
        {
          index++;
        }
      }

      writer.WriteEndArray();

      if (hasWrittenMetadataObject)
        writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);

      contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
    }
Example #19
0
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingCollection, base.Serializer.Context);
            SerializeStack.Add(values.UnderlyingCollection);
            bool flag  = contract.IsReference ?? HasFlag(base.Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
            bool flag2 = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

            if (flag || flag2)
            {
                writer.WriteStartObject();
                if (flag)
                {
                    writer.WritePropertyName("$id");
                    writer.WriteValue(base.Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
                }
                if (flag2)
                {
                    WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
                }
                writer.WritePropertyName("$values");
            }
            JsonContract collectionValueContract2 = base.Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));

            writer.WriteStartArray();
            int top = writer.Top;
            int num = 0;

            foreach (object value in values)
            {
                try
                {
                    JsonContract contractSafe = GetContractSafe(value);
                    if (ShouldWriteReference(value, null, contractSafe))
                    {
                        WriteReference(writer, value);
                    }
                    else if (CheckForCircularReference(value, null, contract))
                    {
                        SerializeValue(writer, value, contractSafe, null, collectionValueContract2);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingCollection, contract, num, ex))
                    {
                        HandleError(writer, top);
                        continue;
                    }
                    throw;
                }
                finally
                {
                    num++;
                }
            }
            writer.WriteEndArray();
            if (flag || flag2)
            {
                writer.WriteEndObject();
            }
            SerializeStack.RemoveAt(SerializeStack.Count - 1);
            contract.InvokeOnSerialized(values.UnderlyingCollection, base.Serializer.Context);
        }
    private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract)
    {
      return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) =>
        {
          if (reference != null && isTemporaryListReference)
            throw CreateSerializationException(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

#if !PocketPC
          if (contract.OnSerializing != null && isTemporaryListReference)
            throw CreateSerializationException(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
#endif
          if (contract.OnError != null && isTemporaryListReference)
            throw CreateSerializationException(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

          PopulateList(contract.CreateWrapper(l), reader, reference, contract);
        });
    }
        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 !(DOTNET || 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;
            }
        }
 private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
 {
   int arrayRank = contract.UnderlyingType.GetArrayRank();
   if (id != null)
     this.AddReference(reader, id, (object) list);
   contract.InvokeOnDeserializing((object) list, this.Serializer.Context);
   JsonContract contractSafe = this.GetContractSafe(contract.CollectionItemType);
   JsonConverter converter = this.GetConverter(contractSafe, (JsonConverter) null, (JsonContainerContract) contract, containerProperty);
   int? nullable1 = new int?();
   Stack<IList> stack = new Stack<IList>();
   stack.Push(list);
   IList list1 = list;
   bool flag = false;
   do
   {
     int depth = reader.Depth;
     if (stack.Count == arrayRank)
     {
       try
       {
         if (this.ReadForType(reader, contractSafe, converter != null))
         {
           switch (reader.TokenType)
           {
             case JsonToken.Comment:
               break;
             case JsonToken.EndArray:
               stack.Pop();
               list1 = stack.Peek();
               nullable1 = new int?();
               break;
             default:
               object obj = converter == null || !converter.CanRead ? this.CreateValueInternal(reader, contract.CollectionItemType, contractSafe, (JsonProperty) null, (JsonContainerContract) contract, containerProperty, (object) null) : converter.ReadJson(reader, contract.CollectionItemType, (object) null, (JsonSerializer) this.GetInternalSerializer());
               list1.Add(obj);
               break;
           }
         }
         else
           break;
       }
       catch (Exception ex)
       {
         JsonPosition position = reader.GetPosition(depth);
         if (this.IsErrorHandled((object) list, (JsonContract) contract, (object) position.Position, reader.Path, ex))
         {
           this.HandleError(reader, true, depth);
           if (nullable1.HasValue)
           {
             int? nullable2 = nullable1;
             int? nullable3 = position.Position;
             if ((nullable2.GetValueOrDefault() != nullable3.GetValueOrDefault() ? 0 : (nullable2.HasValue == nullable3.HasValue ? 1 : 0)) != 0)
               throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
           }
           nullable1 = position.Position;
         }
         else
           throw;
       }
     }
     else if (reader.Read())
     {
       switch (reader.TokenType)
       {
         case JsonToken.StartArray:
           IList list2 = (IList) new List<object>();
           list1.Add((object) list2);
           stack.Push(list2);
           list1 = list2;
           break;
         case JsonToken.Comment:
           break;
         case JsonToken.EndArray:
           stack.Pop();
           if (stack.Count > 0)
           {
             list1 = stack.Peek();
             break;
           }
           else
           {
             flag = true;
             break;
           }
         default:
           throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + (object) reader.TokenType);
       }
     }
     else
       break;
   }
   while (!flag);
   if (!flag)
     this.ThrowUnexpectedEndException(reader, (JsonContract) contract, (object) list, "Unexpected end when deserializing array.");
   contract.InvokeOnDeserialized((object) list, this.Serializer.Context);
   return (object) list;
 }
        private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedCollection wrappedCollection = values as IWrappedCollection;
            object             underlyingList    = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;

            OnSerializing(writer, contract, underlyingList);

            _serializeStack.Add(underlyingList);

            bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int index = 0;

            // note that an error in the IEnumerable won't be caught
            foreach (object value in values)
            {
                try
                {
                    JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract, member))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
                        {
                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    index++;
                }
            }

            writer.WriteEndArray();

            if (hasWrittenMetadataObject)
            {
                writer.WriteEndObject();
            }

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingList);
        }
        private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
            // don't make readonly fields the referenced value because they can't be deserialized to
            isReference = (isReference && (member == null || member.Writable));

            bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
            bool writeMetadataObject = isReference || includeTypeDetails;

            if (writeMetadataObject)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
            }

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

            return writeMetadataObject;
        }
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);

            SerializeStack.Add(values.UnderlyingCollection);

            bool isReference        = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
            bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

            if (isReference || includeTypeDetails)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                    writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
            }

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

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int index = 0;

            // note that an error in the IEnumerable won't be caught
#if !(UNITY_IPHONE || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII) || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII && !(UNITY_3_5 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3))
            foreach (object value in values)
            {
                try
                {
                    JsonContract valueContract = GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(value, null, contract))
                        {
                            SerializeValue(writer, value, valueContract, null, childValuesContract);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    index++;
                }
            }
#else
            values.ForEach(value =>
            {
                try
                {
                    JsonContract valueContract = GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(value, null, contract))
                        {
                            SerializeValue(writer, value, valueContract, null, childValuesContract);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    index++;
                }
            });
#endif

            writer.WriteEndArray();

            if (isReference || includeTypeDetails)
            {
                writer.WriteEndObject();
            }

            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
        }
		private object PopulateMultidimensionalArray(IList list, JsonReader reader, string reference, JsonArrayContract contract)
		{
			int rank = contract.UnderlyingType.GetArrayRank();

			if (reference != null)
				Serializer.ReferenceResolver.AddReference(this, reference, list);

			contract.InvokeOnDeserializing(list, Serializer.Context);

			//JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
			//JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);

			//int? previousErrorIndex = null;
			Stack<IList> listStack = new Stack<IList>();
			listStack.Push(list);
			IList currentList = list;

			bool finished = false;
			do
			{
				int initialDepth = reader.Depth;

				if (listStack.Count == rank)
				{
					if (ReadForTypeArrayHack(reader, contract.CollectionItemType))
					{
						switch (reader.TokenType)
						{
							case JsonToken.EndArray:
								listStack.Pop();
								currentList = listStack.Peek();
								//previousErrorIndex = null;
								break;
							case JsonToken.Comment:
								break;
							default:
								try
								{
									object value = CreateValueNonProperty(reader, contract.CollectionItemType, GetContractSafe(contract.CollectionItemType));

									currentList.Add(value);
								}
								catch (Exception ex)
								{
									if (IsErrorHandled(list, contract, currentList.Count, ex))
										HandleError(reader, initialDepth);
									else
										throw;
								}
								break;
						}
					}
					else
					{
						break;
					}


				}
				else
				{
					if (reader.Read())
					{
						switch (reader.TokenType)
						{
							case JsonToken.StartArray:
								IList newList = new List<object>();
								currentList.Add(newList);
								listStack.Push(newList);
								currentList = newList;
								break;
							case JsonToken.EndArray:
								listStack.Pop();

								if (listStack.Count > 0)
								{
									currentList = listStack.Peek();
								}
								else
								{
									finished = true;
								}
								break;
							case JsonToken.Comment:
								break;
							default:
								throw new JsonSerializationException("Unexpected token when deserializing multidimensional array: " + reader.TokenType);
						}
					}
					else
					{
						break;
					}
				}
			} while (!finished);

			if (!finished)
				throw new JsonSerializationException("Unexpected end when deserializing array." + reader.TokenType);

			contract.InvokeOnDeserialized(list, Serializer.Context);
			return list;
		}
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);

            SerializeStack.Add(values.UnderlyingCollection);
            
            bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
            bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

            if (isReference || includeTypeDetails)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                    writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
            }

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

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int index = 0;
            // note that an error in the IEnumerable won't be caught
            foreach (object value in values)
            {
                try
                {

                    // Note: So apparently the type of the items in the list are being retrieved already in the childValuesContract.  Check to see
                    // if the type here is correct, and check to see if the contract retrieved here is the same as the childValuesContract.
                    JsonContract valueContract = childValuesContract;
 
                    if(value !=  null)
                        valueContract = Serializer.ContractResolver.ResolveContract(value.GetType());
 
                    //JsonContract valueContract = GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(value, null, contract))
                        {
                            SerializeValue(writer, value, valueContract, null, childValuesContract);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
                        HandleError(writer, initialDepth);
                    else
                        throw;
                }
                finally
                {
                    index++;
                }
            }

            writer.WriteEndArray();

            if (isReference || includeTypeDetails)
            {
                writer.WriteEndObject();
            }

            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
        }
    private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
    {
      object list = wrappedList.UnderlyingCollection;

      if (id != null)
        Serializer.ReferenceResolver.AddReference(this, id, list);

      // can't populate an existing array
      if (wrappedList.IsFixedSize)
      {
        reader.Skip();
        return list;
      }

      contract.InvokeOnDeserializing(list, Serializer.Context);

      int initialDepth = reader.Depth;

      JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
      JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);

      int? previousErrorIndex = null;

      while (true)
      {
        try
        {
          if (ReadForType(reader, collectionItemContract, collectionItemConverter != null))
          {
            switch (reader.TokenType)
            {
              case JsonToken.EndArray:
                contract.InvokeOnDeserialized(list, Serializer.Context);

                return list;
              case JsonToken.Comment:
                break;
              default:
                object value;

                if (collectionItemConverter != null && collectionItemConverter.CanRead)
                  value = collectionItemConverter.ReadJson(reader, contract.CollectionItemType, null, GetInternalSerializer());
                else
                  value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null);

                wrappedList.Add(value);
                break;
            }
          }
          else
          {
            break;
          }
        }
        catch (Exception ex)
        {
          JsonPosition errorPosition = reader.GetPosition(initialDepth);

          if (IsErrorHandled(list, contract, errorPosition.Position, reader.Path, ex))
          {
            HandleError(reader, true, initialDepth);

            if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
            {
              // reader index has not moved since previous error handling
              // break out of reading array to prevent infinite loop
              throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
            }
            else
            {
              previousErrorIndex = errorPosition.Position;
            }
          }
          else
          {
            throw;
          }
        }
      }

      throw JsonSerializationException.Create(reader, "Unexpected end when deserializing array.");
    }
 private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
   contract.InvokeOnSerializing(values.UnderlyingCollection, this.Serializer.Context);
   this._serializeStack.Add(values.UnderlyingCollection);
   bool flag = this.WriteStartArray(writer, values.UnderlyingCollection, contract, member, collectionContract, containerProperty);
   writer.WriteStartArray();
   int top = writer.Top;
   int num = 0;
   foreach (object obj in (IEnumerable) values)
   {
     try
     {
       JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(obj);
       if (this.ShouldWriteReference(obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
         this.WriteReference(writer, obj);
       else if (this.CheckForCircularReference(writer, obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
         this.SerializeValue(writer, obj, jsonContract, (JsonProperty) null, (JsonContainerContract) contract, member);
     }
     catch (Exception ex)
     {
       if (this.IsErrorHandled(values.UnderlyingCollection, (JsonContract) contract, (object) num, writer.ContainerPath, ex))
         this.HandleError(writer, top);
       else
         throw;
     }
     finally
     {
       ++num;
     }
   }
   writer.WriteEndArray();
   if (flag)
     writer.WriteEndObject();
   this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
   contract.InvokeOnSerialized(values.UnderlyingCollection, this.Serializer.Context);
 }
        /// <summary>
        /// Creates a <see cref="JsonArrayContract"/> for the given type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>A <see cref="JsonArrayContract"/> for the given type.</returns>
        protected virtual JsonArrayContract CreateArrayContract(Type objectType)
        {
            JsonArrayContract contract = new JsonArrayContract(objectType);
              InitializeContract(contract);

              return contract;
        }
 private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
   contract.InvokeOnSerializing((object) values, this.Serializer.Context);
   this._serializeStack.Add((object) values);
   bool flag = this.WriteStartArray(writer, (object) values, contract, member, collectionContract, containerProperty);
   this.SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
   if (flag)
     writer.WriteEndObject();
   this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
   contract.InvokeOnSerialized((object) values, this.Serializer.Context);
 }
		private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
		{
			contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);

			SerializeStack.Add(values.UnderlyingCollection);

			bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
			bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

			if (isReference || includeTypeDetails)
			{
				writer.WriteStartObject();

				if (isReference)
				{
					writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
					writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
				}
				if (includeTypeDetails)
				{
					WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
				}
				writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
			}

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

			writer.WriteStartArray();

			int initialDepth = writer.Top;

			int index = 0;
			// note that an error in the IEnumerable won't be caught
#if !(UNITY_IPHONE || UNITY_IOS)
			foreach (object value in values)
			{
				try
				{
					JsonContract valueContract = GetContractSafe(value);

					if (ShouldWriteReference(value, null, valueContract))
					{
						WriteReference(writer, value);
					}
					else
					{
						if (CheckForCircularReference(value, null, contract))
						{
							SerializeValue(writer, value, valueContract, null, childValuesContract);
						}
					}
				}
				catch (Exception ex)
				{
					if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
						HandleError(writer, initialDepth);
					else
						throw;
				}
				finally
				{
					index++;
				}
			}
#else

			values.ForEach(value =>
			{
				try
				{
					JsonContract valueContract = GetContractSafe(value);

					if (ShouldWriteReference(value, null, valueContract))
					{
						WriteReference(writer, value);
					}
					else
					{
						if (CheckForCircularReference(value, null, contract))
						{
							SerializeValue(writer, value, valueContract, null, childValuesContract);
						}
					}
				}
				catch (Exception ex)
				{
					if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
						HandleError(writer, initialDepth);
					else
						throw;
				}
				finally
				{
					index++;
				}
			});


#endif

			writer.WriteEndArray();

			if (isReference || includeTypeDetails)
			{
				writer.WriteEndObject();
			}

			SerializeStack.RemoveAt(SerializeStack.Count - 1);

			contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
		}
 private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
 {
   int length = indices.Length;
   int[] indices1 = new int[length + 1];
   for (int index = 0; index < length; ++index)
     indices1[index] = indices[index];
   writer.WriteStartArray();
   for (int index = 0; index < values.GetLength(length); ++index)
   {
     indices1[length] = index;
     if (indices1.Length == values.Rank)
     {
       object obj = values.GetValue(indices1);
       try
       {
         JsonContract jsonContract = contract.FinalItemContract ?? this.GetContractSafe(obj);
         if (this.ShouldWriteReference(obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
           this.WriteReference(writer, obj);
         else if (this.CheckForCircularReference(writer, obj, (JsonProperty) null, jsonContract, (JsonContainerContract) contract, member))
           this.SerializeValue(writer, obj, jsonContract, (JsonProperty) null, (JsonContainerContract) contract, member);
       }
       catch (Exception ex)
       {
         if (this.IsErrorHandled((object) values, (JsonContract) contract, (object) index, writer.ContainerPath, ex))
           this.HandleError(writer, initialDepth + 1);
         else
           throw;
       }
     }
     else
       this.SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, indices1);
   }
   writer.WriteEndArray();
 }
        private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
        {
            IWrappedCollection wrappedCollection = list as IWrappedCollection;
              object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : list;

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

              // can't populate an existing array
              if (list.IsFixedSize)
              {
            reader.Skip();
            return underlyingList;
              }

              OnDeserializing(reader, contract, underlyingList);

              int initialDepth = reader.Depth;

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

              JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty);

              int? previousErrorIndex = null;

              bool finished = false;
              do
              {
            try
            {
              if (ReadForType(reader, contract.ItemContract, collectionItemConverter != null))
              {
            switch (reader.TokenType)
            {
              case JsonToken.EndArray:
                finished = true;
                break;
              case JsonToken.Comment:
                break;
              default:
                object value;

                if (collectionItemConverter != null && collectionItemConverter.CanRead)
                  value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
                else
                  value = CreateValueInternal(reader, contract.CollectionItemType, contract.ItemContract, null, contract, containerProperty, null);

                list.Add(value);
                break;
            }
              }
              else
              {
            break;
              }
            }
            catch (Exception ex)
            {
              JsonPosition errorPosition = reader.GetPosition(initialDepth);

              if (IsErrorHandled(underlyingList, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex))
              {
            HandleError(reader, true, initialDepth);

            if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
            {
              // reader index has not moved since previous error handling
              // break out of reading array to prevent infinite loop
              throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
            }
            else
            {
              previousErrorIndex = errorPosition.Position;
            }
              }
              else
              {
            throw;
              }
            }
              } while (!finished);

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

              OnDeserialized(reader, contract, underlyingList);
              return underlyingList;
        }
 private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
 {
   bool? nullable = this.ResolveIsReference((JsonContract) contract, member, containerContract, containerProperty);
   bool flag1 = nullable.HasValue ? nullable.GetValueOrDefault() : this.HasFlag(this.Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
   bool flag2 = this.ShouldWriteType(TypeNameHandling.Arrays, (JsonContract) contract, member, containerContract, containerProperty);
   bool flag3 = flag1 || flag2;
   if (flag3)
   {
     writer.WriteStartObject();
     if (flag1)
     {
       writer.WritePropertyName("$id");
       writer.WriteValue(this.GetReference(writer, values));
     }
     if (flag2)
       this.WriteTypeProperty(writer, values.GetType());
     writer.WritePropertyName("$values");
   }
   if (contract.ItemContract == null)
     contract.ItemContract = this.Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof (object));
   return flag3;
 }
        private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultConstructor)
        {
            // some types like non-generic IEnumerable can be serialized but not deserialized
              if (!contract.CanDeserialize)
            throw JsonSerializationException.Create(reader, "Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType));

              if (contract.IsReadOnlyOrFixedSize)
              {
            createdFromNonDefaultConstructor = true;
            IList list = contract.CreateTemporaryCollection();

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

            return list;
              }
              else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
              {
            object list = contract.DefaultCreator();

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

            createdFromNonDefaultConstructor = false;
            return (IList)list;
              }
              else if (contract.ParametrizedConstructor != null)
              {
            createdFromNonDefaultConstructor = true;
            return contract.CreateTemporaryCollection();
              }
              else
              {
            throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
              }
        }
        private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract)
        {
            return CollectionUtils.CreateAndPopulateList(contract.CollectionTypeToCreate, (l, isTemporaryListReference) =>
            {
              if (reference != null && isTemporaryListReference)
            throw new JsonSerializationException("Cannot preserve reference to array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));

            #if !PocketPC && !SILVERLIGHT
              if (contract.OnSerializing != null && isTemporaryListReference)
            throw new JsonSerializationException("Cannot call OnSerializing on an array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
            #endif

              PopulateList(l, reader, reference, contract);
            });
        }
    private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      contract.InvokeOnSerializing(values, Serializer.Context);

      _serializeStack.Add(values);

      bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);

      SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);

      if (hasWrittenMetadataObject)
        writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);

      contract.InvokeOnSerialized(values, Serializer.Context);
    }
        private IList PopulateList(IList list, JsonReader reader, string reference, JsonArrayContract contract)
        {
            if (reference != null)
            _serializer.ReferenceResolver.AddReference(reference, list);

              contract.InvokeOnDeserializing(list);

              while (reader.Read())
              {
            switch (reader.TokenType)
            {
              case JsonToken.EndArray:
            contract.InvokeOnDeserialized(list);

            return list;
              case JsonToken.Comment:
            break;
              default:
            object value = CreateValue(reader, contract.CollectionItemType, null, null);

            list.Add(value);
            break;
            }
              }

              throw new JsonSerializationException("Unexpected end when deserializing array.");
        }
    private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
    {
      bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
      bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
      bool writeMetadataObject = isReference || includeTypeDetails;

      if (writeMetadataObject)
      {
        writer.WriteStartObject();

        if (isReference)
        {
          writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
          writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values));
        }
        if (includeTypeDetails)
        {
          WriteTypeProperty(writer, values.GetType());
        }
        writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
      }

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

      return writeMetadataObject;
    }
		private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) {
			OnSerializing(writer, contract, values.UnderlyingCollection);

			_serializeStack.Add(values.UnderlyingCollection);

			bool hasWrittenMetadataObject = WriteStartArray(writer, values.UnderlyingCollection, contract, member, collectionContract, containerProperty);

			writer.WriteStartArray();

			int initialDepth = writer.Top;

			int index = 0;
			object valuePrevious = new object();
			try {
				// note that an error in the IEnumerable won't be caught
				foreach (object value in values) {
					try {
						JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

						if (ShouldWriteReference(value, null, valueContract, contract, member)) {
							WriteReference(writer, value);
						} else {
							if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) {
								SerializeValue(writer, value, valueContract, null, contract, member);
							}
						}
					} catch (Exception ex) {
						if (IsErrorHandled(values.UnderlyingCollection, contract, index, null, writer.ContainerPath, ex))
							HandleError(writer, initialDepth);
						else
							throw;
					} finally {
						index++;
						valuePrevious = value;
					}
				}
			} catch (Exception e) {
				string msg = "valuePrevious[" + valuePrevious.ToString() + "] trying to catch COLLECTION_CHANGED";
				throw new Exception(msg, e);
			}

			writer.WriteEndArray();

			if (hasWrittenMetadataObject)
				writer.WriteEndObject();

			_serializeStack.RemoveAt(_serializeStack.Count - 1);

			OnSerialized(writer, contract, values.UnderlyingCollection);
		}
    private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, string reference, JsonArrayContract contract)
    {
      object list = wrappedList.UnderlyingCollection;

      // can't populate an existing array
      if (wrappedList.IsFixedSize)
      {
        reader.Skip();
        return wrappedList.UnderlyingCollection;
      }

      if (reference != null)
        Serializer.ReferenceResolver.AddReference(this, reference, list);

      contract.InvokeOnDeserializing(list, Serializer.Context);

      int initialDepth = reader.Depth;
      int index = 0;

      JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
      JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null);

      while (true)
      {
        try
        {
          if (ReadForType(reader, collectionItemContract, collectionItemConverter != null, true))
          {
            switch (reader.TokenType)
            {
              case JsonToken.EndArray:
                contract.InvokeOnDeserialized(list, Serializer.Context);

                return wrappedList.UnderlyingCollection;
              case JsonToken.Comment:
                break;
              default:
                object value = CreateValueNonProperty(reader, contract.CollectionItemType, collectionItemContract, collectionItemConverter);

                wrappedList.Add(value);
                break;
            }
          }
          else
          {
            break;
          }
        }
        catch (Exception ex)
        {
          if (IsErrorHandled(list, contract, index, reader.Path, ex))
            HandleError(reader, initialDepth);
          else
            throw;
        }
        finally
        {
          index++;
        }
      }

      throw CreateSerializationException(reader, "Unexpected end when deserializing array.");
    }
Example #43
0
        private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);

            _serializeStack.Add(values.UnderlyingCollection);

            bool isReference        = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
            bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);

            if (isReference || includeTypeDetails)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                    writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
            }

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

            JsonContract collectionItemValueContract = (contract.CollectionItemContract.UnderlyingType.IsSealed) ? contract.CollectionItemContract : null;

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int index = 0;

            // note that an error in the IEnumerable won't be caught
            foreach (object value in values)
            {
                try
                {
                    JsonContract valueContract = collectionItemValueContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(value, null, contract))
                        {
                            SerializeValue(writer, value, valueContract, null, contract.CollectionItemContract);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    index++;
                }
            }

            writer.WriteEndArray();

            if (isReference || includeTypeDetails)
            {
                writer.WriteEndObject();
            }

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
        }