Contract details for a Type used by the JsonSerializer.
Inheritance: Newtonsoft.Json.Serialization.JsonContainerContract
        public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member)
        {
            ValidationUtils.ArgumentNotNull(reader, "serializer");
            ValidationUtils.ArgumentNotNull(contract, "contract");

            _reader   = reader;
            _contract = contract;
            _member   = member;
        }
 public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member)
 {
     Class6.yDnXvgqzyB5jw();
     base();
     ValidationUtils.ArgumentNotNull(reader, "reader");
     ValidationUtils.ArgumentNotNull(contract, "contract");
     this._reader   = reader;
     this._contract = contract;
     this._member   = member;
 }
示例#3
0
 public JsonFormatterConverter(
     JsonSerializerInternalReader reader,
     JsonISerializableContract contract,
     JsonProperty member)
 {
     ValidationUtils.ArgumentNotNull((object)reader, nameof(reader));
     ValidationUtils.ArgumentNotNull((object)contract, nameof(contract));
     this._reader   = reader;
     this._contract = contract;
     this._member   = member;
 }
示例#4
0
        private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
        {
            Type objectType = contract.UnderlyingType;

            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());

            bool exit = false;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string memberName = reader.Value.ToString();
                    if (!reader.Read())
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
                    }

                    serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
                    break;

                case JsonToken.Comment:
                    break;

                case JsonToken.EndObject:
                    exit = true;
                    break;

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

            if (contract.ISerializableCreator == null)
            {
                throw new JsonSerializationException("ISerializable type '{0}' does not have a valid constructor.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }

            object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);

            if (id != null)
            {
                Serializer.ReferenceResolver.AddReference(this, id, createdObject);
            }

            // these are together because OnDeserializing takes an object but for an ISerializable the object is full created in the constructor
            contract.InvokeOnDeserializing(createdObject, Serializer.Context);
            contract.InvokeOnDeserialized(createdObject, Serializer.Context);

            return(createdObject);
        }
示例#5
0
        protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
        {
            JsonISerializableContract jsonISerializableContract = new JsonISerializableContract(objectType);

            this.InitializeContract(jsonISerializableContract);
            ConstructorInfo constructor = objectType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

            if (constructor != null)
            {
                MethodCall <object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall <object>(constructor);
                jsonISerializableContract.ISerializableCreator = (object[] args) => methodCall(null, args);
            }
            return(jsonISerializableContract);
        }
        protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
        {
            JsonISerializableContract contract = new JsonISerializableContract(objectType);

            this.method_7(contract);
            ConstructorInfo info = contract.type_0.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

            if (info != null)
            {
                Class127 class2 = new Class127 {
                    delegate3_0 = Class139.Class166_0.ns20.Class166.‫‌‪‭‭‪‌‎‮‬​‌‌‬‎‮‌‏‌‎‪‌‏‬‫‭‮ <object>(info)
                };
                contract.ISerializableCreator = new ObjectConstructor <object>(class2.method_0);
            }
            return(contract);
        }
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
        {
            contract.InvokeOnSerializing(value, base.Serializer.Context);
            this.SerializeStack.Add(value);
            writer.WriteStartObject();
            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, base.Serializer.Context);
            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                writer.WritePropertyName(serializationEntry.Name);
                this.SerializeValue(writer, serializationEntry.Value, this.GetContractSafe(serializationEntry.Value), null, null);
            }
            writer.WriteEndObject();
            this.SerializeStack.RemoveAt(this.SerializeStack.Count - 1);
            contract.InvokeOnSerialized(value, base.Serializer.Context);
        }
示例#8
0
        private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
        {
            Type underlyingType = contract.UnderlyingType;
            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());
            bool flag = false;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                {
                    string text = reader.Value.ToString();
                    if (!reader.Read())
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, text));
                    }
                    serializationInfo.AddValue(text, JToken.ReadFrom(reader));
                    break;
                }

                case JsonToken.EndObject:
                    flag = true;
                    break;

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

                case JsonToken.Comment:
                    break;
                }
            }while (!flag && reader.Read());
            if (contract.ISerializableCreator == null)
            {
                throw new JsonSerializationException("ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, underlyingType));
            }
            object obj = contract.ISerializableCreator(serializationInfo, base.Serializer.Context);

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, obj);
            }
            contract.InvokeOnDeserializing(obj, base.Serializer.Context);
            contract.InvokeOnDeserialized(obj, base.Serializer.Context);
            return(obj);
        }
        /// <summary>
        /// Creates a <see cref="JsonISerializableContract"/> for the given type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>A <see cref="JsonISerializableContract"/> for the given type.</returns>
        protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
        {
            JsonISerializableContract contract = new JsonISerializableContract(objectType);

            InitializeContract(contract);

            ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

            if (constructorInfo != null)
            {
                MethodCall <object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall <object>(constructorInfo);

                contract.ISerializableCreator = (args => methodCall(null, args));
            }

            return(contract);
        }
示例#10
0
        protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
        {
            JsonISerializableContract iserializableContract = new JsonISerializableContract(objectType);

            this.InitializeContract((JsonContract)iserializableContract);
            ConstructorInfo constructor = iserializableContract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, (Binder)null, new Type[2]
            {
                typeof(SerializationInfo),
                typeof(StreamingContext)
            }, (ParameterModifier[])null);

            if (constructor != null)
            {
                MethodCall <object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall <object>((MethodBase)constructor);
                iserializableContract.ISerializableCreator = (ObjectConstructor <object>)(args => methodCall((object)null, args));
            }
            return(iserializableContract);
        }
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
        {
            contract.InvokeOnSerializing(value, base.Serializer.Context);
            SerializeStack.Add(value);
            writer.WriteStartObject();
            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, base.Serializer.Context);
            SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SerializationEntry current = enumerator.Current;
                writer.WritePropertyName(current.Name);
                SerializeValue(writer, current.Value, GetContractSafe(current.Value), null, null);
            }
            writer.WriteEndObject();
            SerializeStack.RemoveAt(SerializeStack.Count - 1);
            contract.InvokeOnSerialized(value, base.Serializer.Context);
        }
示例#12
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
                                 @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
                message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());

                throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
            }

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

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

            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, Serializer._context);

            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                JsonContract valueContract = GetContractSafe(serializationEntry.Value);

                if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    WriteReference(writer, serializationEntry.Value);
                }
                else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);
            OnSerialized(writer, contract, value);
        }
示例#13
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                throw JsonSerializationException.Create((IJsonLineInfo)null, writer.ContainerPath, StringUtils.FormatWith("Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.\r\nTo fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.", (IFormatProvider)CultureInfo.InvariantCulture, (object)value.GetType()), (Exception)null);
            }
            contract.InvokeOnSerializing((object)value, this.Serializer.Context);
            this._serializeStack.Add((object)value);
            this.WriteObjectStart(writer, (object)value, (JsonContract)contract, member, collectionContract, containerProperty);
            SerializationInfo info = new SerializationInfo(contract.UnderlyingType, (IFormatterConverter) new FormatterConverter());

            value.GetObjectData(info, this.Serializer.Context);
            foreach (SerializationEntry serializationEntry in info)
            {
                writer.WritePropertyName(serializationEntry.Name);
                this.SerializeValue(writer, serializationEntry.Value, this.GetContractSafe(serializationEntry.Value), (JsonProperty)null, (JsonContainerContract)null, member);
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            contract.InvokeOnSerialized((object)value, this.Serializer.Context);
        }
示例#14
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                string str = string.Concat("Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.", Environment.NewLine, "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.", Environment.NewLine);
                str = str.FormatWith(CultureInfo.InvariantCulture, value.GetType());
                throw JsonSerializationException.Create(null, writer.ContainerPath, str, null);
            }
            this.OnSerializing(writer, contract, value);
            this._serializeStack.Add(value);
            this.WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, this.Serializer._context);
            SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SerializationEntry current      = enumerator.Current;
                JsonContract       contractSafe = this.GetContractSafe(current.Value);
                if (!this.ShouldWriteReference(current.Value, null, contractSafe, contract, member))
                {
                    if (!this.CheckForCircularReference(writer, current.Value, null, contractSafe, contract, member))
                    {
                        continue;
                    }
                    writer.WritePropertyName(current.Name);
                    this.SerializeValue(writer, current.Value, contractSafe, null, contract, member);
                }
                else
                {
                    writer.WritePropertyName(current.Name);
                    this.WriteReference(writer, current.Value);
                }
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            this.OnSerialized(writer, contract, value);
        }
 // Token: 0x06000C07 RID: 3079
 // RVA: 0x00047744 File Offset: 0x00045944
 private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
     if (!JsonTypeReflector.FullyTrusted)
     {
         string text = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
         text = StringUtils.FormatWith(text, CultureInfo.InvariantCulture, value.GetType());
         throw JsonSerializationException.Create(null, writer.ContainerPath, text, null);
     }
     this.OnSerializing(writer, contract, value);
     this._serializeStack.Add(value);
     this.WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
     SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
     value.GetObjectData(serializationInfo, this.Serializer._context);
     SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();
     while (enumerator.MoveNext())
     {
         SerializationEntry current = enumerator.Current;
         JsonContract contractSafe = this.GetContractSafe(current.Value);
         if (this.ShouldWriteReference(current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.WriteReference(writer, current.Value);
         }
         else if (this.CheckForCircularReference(writer, current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.SerializeValue(writer, current.Value, contractSafe, null, contract, member);
         }
     }
     writer.WriteEndObject();
     this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
     this.OnSerialized(writer, contract, value);
 }
    private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
    {
      Type objectType = contract.UnderlyingType;

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());

      bool exit = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
            break;
          case JsonToken.EndObject:
            exit = true;
            break;
          default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!exit && reader.Read());

      if (contract.ISerializableCreator == null)
        throw new JsonSerializationException("ISerializable type '{0}' does not have a valid constructor.".FormatWith(CultureInfo.InvariantCulture, objectType));

      object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);

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

      contract.InvokeOnDeserializing(createdObject, Serializer.Context);
      contract.InvokeOnDeserialized(createdObject, Serializer.Context);

      return createdObject;
    }
		private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
		{
			contract.InvokeOnSerializing(value, Serializer.Context);
			SerializeStack.Add(value);

			writer.WriteStartObject();

			SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
			value.GetObjectData(serializationInfo, Serializer.Context);

			foreach (SerializationEntry serializationEntry in serializationInfo)
			{
				writer.WritePropertyName(serializationEntry.Name);
				SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
			}

			writer.WriteEndObject();

			SerializeStack.RemoveAt(SerializeStack.Count - 1);
			contract.InvokeOnSerialized(value, Serializer.Context);
		}
 // Token: 0x06000BD6 RID: 3030
 // RVA: 0x00045708 File Offset: 0x00043908
 internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member)
 {
     JsonContract contractSafe = this.GetContractSafe(type);
     JsonConverter converter = this.GetConverter(contractSafe, null, contract, member);
     JsonReader reader = token.CreateReader();
     this.CheckedRead(reader);
     object result;
     if (converter != null && converter.CanRead)
     {
         result = this.DeserializeConvertable(converter, reader, type, null);
     }
     else
     {
         result = this.CreateValueInternal(reader, type, contractSafe, null, contract, member, null);
     }
     return result;
 }
 // Token: 0x06000BD5 RID: 3029
 // RVA: 0x00045544 File Offset: 0x00043744
 private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id)
 {
     Type underlyingType = contract.UnderlyingType;
     if (!JsonTypeReflector.FullyTrusted)
     {
         string text = "Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
         text = StringUtils.FormatWith(text, CultureInfo.InvariantCulture, underlyingType);
         throw JsonSerializationException.Create(reader, text);
     }
     if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Info)
     {
         this.TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("Deserializing {0} using ISerializable constructor.", CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
     }
     SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new JsonFormatterConverter(this, contract, member));
     bool flag = false;
     string text2;
     do
     {
         JsonToken tokenType = reader.TokenType;
         switch (tokenType)
         {
         case JsonToken.PropertyName:
             text2 = reader.Value.ToString();
             if (!reader.Read())
             {
                 goto IL_119;
             }
             serializationInfo.AddValue(text2, JToken.ReadFrom(reader));
             break;
         case JsonToken.Comment:
             break;
         default:
             if (tokenType != JsonToken.EndObject)
             {
                 goto Block_7;
             }
             flag = true;
             break;
         }
         if (flag)
         {
             break;
         }
     }
     while (reader.Read());
     goto IL_131;
     Block_7:
     throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
     IL_119:
     throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected end when setting {0}'s value.", CultureInfo.InvariantCulture, text2));
     IL_131:
     if (!flag)
     {
         this.ThrowUnexpectedEndException(reader, contract, serializationInfo, "Unexpected end when deserializing object.");
     }
     if (contract.ISerializableCreator == null)
     {
         throw JsonSerializationException.Create(reader, StringUtils.FormatWith("ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.", CultureInfo.InvariantCulture, underlyingType));
     }
     object obj = contract.ISerializableCreator(new object[]
     {
         serializationInfo,
         this.Serializer._context
     });
     if (id != null)
     {
         this.AddReference(reader, id, obj);
     }
     this.OnDeserializing(reader, contract, obj);
     this.OnDeserialized(reader, contract, obj);
     return obj;
 }
示例#20
0
 protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
 {
   JsonISerializableContract iserializableContract = new JsonISerializableContract(objectType);
   this.InitializeContract((JsonContract) iserializableContract);
   ConstructorInfo constructor = iserializableContract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, (Binder) null, new Type[2]
   {
     typeof (SerializationInfo),
     typeof (StreamingContext)
   }, (ParameterModifier[]) null);
   if (constructor != null)
   {
     MethodCall<object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>((MethodBase) constructor);
     iserializableContract.ISerializableCreator = (ObjectConstructor<object>) (args => methodCall((object) null, args));
   }
   return iserializableContract;
 }
示例#21
0
 private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
 {
   CurrentSchema.AllowAdditionalProperties = true;
 }
        internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member)
        {
            JsonContract itemContract = GetContractSafe(type);
            JsonConverter itemConverter = GetConverter(itemContract, null, contract, member);

            JsonReader tokenReader = token.CreateReader();
            CheckedRead(tokenReader); // Move to first token

            object result;
            if (itemConverter != null && itemConverter.CanRead)
                result = DeserializeConvertable(itemConverter, tokenReader, type, null);
            else
                result = CreateValueInternal(tokenReader, type, itemContract, null, contract, member, null);

            return result;
        }
示例#23
0
 private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
 {
   Type underlyingType = contract.UnderlyingType;
   if (!JsonTypeReflector.FullyTrusted)
     throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.\r\nTo fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.\r\n", (IFormatProvider) CultureInfo.InvariantCulture, (object) underlyingType));
   SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, (IFormatterConverter) this.GetFormatterConverter());
   bool flag = false;
   do
   {
     switch (reader.TokenType)
     {
       case JsonToken.PropertyName:
         string name = reader.Value.ToString();
         if (!reader.Read())
           throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected end when setting {0}'s value.", (IFormatProvider) CultureInfo.InvariantCulture, (object) name));
         serializationInfo.AddValue(name, (object) JToken.ReadFrom(reader));
         goto case JsonToken.Comment;
       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, (object) serializationInfo, "Unexpected end when deserializing object.");
   if (contract.ISerializableCreator == null)
     throw JsonSerializationException.Create(reader, StringUtils.FormatWith("ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.", (IFormatProvider) CultureInfo.InvariantCulture, (object) underlyingType));
   object o = contract.ISerializableCreator(new object[2]
   {
     (object) serializationInfo,
     (object) this.Serializer.Context
   });
   if (id != null)
     this.AddReference(reader, id, o);
   contract.InvokeOnDeserializing(o, this.Serializer.Context);
   contract.InvokeOnDeserialized(o, this.Serializer.Context);
   return o;
 }
示例#24
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 object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
    {
      Type objectType = contract.UnderlyingType;

      if (!JsonTypeReflector.FullyTrusted)
      {
        throw JsonSerializationException.Create(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
".FormatWith(CultureInfo.InvariantCulture, objectType));
      }

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());

      bool exit = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            exit = true;
            break;
          default:
            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!exit && reader.Read());

      if (contract.ISerializableCreator == null)
        throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType));

      object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);

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

      // these are together because OnDeserializing takes an object but for an ISerializable the object is fully created in the constructor
      contract.InvokeOnDeserializing(createdObject, Serializer.Context);
      contract.InvokeOnDeserialized(createdObject, Serializer.Context);

      return createdObject;
    }
    private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
    {
      Type objectType = contract.UnderlyingType;

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());

      bool exit = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            exit = true;
            break;
          default:
            throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!exit && reader.Read());

      if (contract.ISerializableCreator == null)
        throw CreateSerializationException(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType));

      object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);

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

      // these are together because OnDeserializing takes an object but for an ISerializable the object is full created in the constructor
      contract.InvokeOnDeserializing(createdObject, Serializer.Context);
      contract.InvokeOnDeserialized(createdObject, Serializer.Context);

      return createdObject;
    }
    private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      if (!JsonTypeReflector.FullyTrusted)
      {
        throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
      }

      contract.InvokeOnSerializing(value, Serializer.Context);
      _serializeStack.Add(value);

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

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
      value.GetObjectData(serializationInfo, Serializer.Context);

      foreach (SerializationEntry serializationEntry in serializationInfo)
      {
        writer.WritePropertyName(serializationEntry.Name);
        SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null, member);
      }

      writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);
      contract.InvokeOnSerialized(value, Serializer.Context);
    }
示例#28
0
        private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue)
        {
            CheckedRead(reader);
            string text = null;

            if (reader.TokenType == JsonToken.PropertyName)
            {
                bool flag;
                do
                {
                    string a = reader.Value.ToString();
                    if (string.Equals(a, "$ref", StringComparison.Ordinal))
                    {
                        CheckedRead(reader);
                        if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
                        {
                            throw new JsonSerializationException("JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, "$ref"));
                        }
                        string text2 = ((reader.Value != null) ? reader.Value.ToString() : null);
                        CheckedRead(reader);
                        if (text2 != null)
                        {
                            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, "$ref"));
                            }
                            return(base.Serializer.ReferenceResolver.ResolveReference(this, text2));
                        }
                        flag = true;
                    }
                    else if (string.Equals(a, "$type", StringComparison.Ordinal))
                    {
                        CheckedRead(reader);
                        string text3 = reader.Value.ToString();
                        CheckedRead(reader);
                        if ((member?.TypeNameHandling ?? base.Serializer.TypeNameHandling) != 0)
                        {
                            ReflectionUtils.SplitFullyQualifiedTypeName(text3, out var typeName, out var assemblyName);
                            Type type;
                            try
                            {
                                type = base.Serializer.Binder.BindToType(assemblyName, typeName);
                            }
                            catch (Exception innerException)
                            {
                                throw new JsonSerializationException("Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, text3), innerException);
                            }
                            if (type == null)
                            {
                                throw new JsonSerializationException("Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, text3));
                            }
                            if (!(objectType?.IsAssignableFrom(type) ?? true))
                            {
                                throw new JsonSerializationException("Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, type.AssemblyQualifiedName, objectType.AssemblyQualifiedName));
                            }
                            objectType = type;
                            contract   = GetContractSafe(type);
                        }
                        flag = true;
                    }
                    else if (string.Equals(a, "$id", StringComparison.Ordinal))
                    {
                        CheckedRead(reader);
                        text = ((reader.Value != null) ? reader.Value.ToString() : null);
                        CheckedRead(reader);
                        flag = true;
                    }
                    else
                    {
                        if (string.Equals(a, "$values", StringComparison.Ordinal))
                        {
                            CheckedRead(reader);
                            object result = CreateList(reader, objectType, contract, member, existingValue, text);
                            CheckedRead(reader);
                            return(result);
                        }
                        flag = false;
                    }
                }while (flag && 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 jsonDictionaryContract = contract as JsonDictionaryContract;

            if (jsonDictionaryContract != null)
            {
                if (existingValue == null)
                {
                    return(CreateAndPopulateDictionary(reader, jsonDictionaryContract, text));
                }
                return(PopulateDictionary(jsonDictionaryContract.CreateWrapper(existingValue), reader, jsonDictionaryContract, text));
            }
            JsonObjectContract jsonObjectContract = contract as JsonObjectContract;

            if (jsonObjectContract != null)
            {
                if (existingValue == null)
                {
                    return(CreateAndPopulateObject(reader, jsonObjectContract, text));
                }
                return(PopulateObject(existingValue, reader, jsonObjectContract, text));
            }
            JsonPrimitiveContract jsonPrimitiveContract = contract as JsonPrimitiveContract;

            if (jsonPrimitiveContract != null && reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), "$value", StringComparison.Ordinal))
            {
                CheckedRead(reader);
                object result2 = CreateValueInternal(reader, objectType, jsonPrimitiveContract, member, existingValue);
                CheckedRead(reader);
                return(result2);
            }
            JsonISerializableContract jsonISerializableContract = contract as JsonISerializableContract;

            if (jsonISerializableContract != null)
            {
                return(CreateISerializable(reader, jsonISerializableContract, text));
            }
            throw new JsonSerializationException("Cannot deserialize JSON object into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
        }
示例#29
-3
        private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id)
        {
            Type objectType = contract.UnderlyingType;

              if (!JsonTypeReflector.FullyTrusted)
              {
            throw JsonSerializationException.Create(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
            To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
            ".FormatWith(CultureInfo.InvariantCulture, objectType));
              }

              if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
            TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using ISerializable constructor.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);

              SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());

              bool finished = false;
              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            if (reader.TokenType == JsonToken.StartObject)
            {
              // this will read any potential type names embedded in json
              object o = CreateObject(reader, null, null, null, contract, member, null);
              serializationInfo.AddValue(memberName, o);
            }
            else
            {
              serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
            }
            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, serializationInfo, "Unexpected end when deserializing object.");

              if (contract.ISerializableCreator == null)
            throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType));

              object createdObject = contract.ISerializableCreator(serializationInfo, Serializer._context);

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

              // these are together because OnDeserializing takes an object but for an ISerializable the object is fully created in the constructor
              OnDeserializing(reader, contract, createdObject);
              OnDeserialized(reader, contract, createdObject);

              return createdObject;
        }