public void JsonSerializationException()
        {
            JsonSerializationException exception = new JsonSerializationException();
            Assert.AreEqual("Exception of type 'Newtonsoft.Json.JsonSerializationException' was thrown.", exception.Message);

            exception = new JsonSerializationException("Message!");
            Assert.AreEqual("Message!", exception.Message);
            Assert.AreEqual(null, exception.InnerException);

            exception = new JsonSerializationException("Message!", new Exception("Inner!"));
            Assert.AreEqual("Message!", exception.Message);
            Assert.AreEqual("Inner!", exception.InnerException.Message);
        }
        public void JsonSerializationException()
        {
            JsonSerializationException exception = new JsonSerializationException();
            Assert.Equal("Exception of type 'OpenGamingLibrary.Json.JsonSerializationException' was thrown.", exception.Message);

            exception = new JsonSerializationException("Message!");
            Assert.Equal("Message!", exception.Message);
            Assert.Equal(null, exception.InnerException);

            exception = new JsonSerializationException("Message!", new Exception("Inner!"));
            Assert.Equal("Message!", exception.Message);
            Assert.Equal("Inner!", exception.InnerException.Message);
        }
Exemple #3
0
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(reader,
                                                            "Cannot convert null value to {0}.".FormatWith((IFormatProvider)CultureInfo.InvariantCulture,
                                                                                                           (object)objectType));
                }
                return((object)null);
            }

            byte[] numArray;
            if (reader.TokenType == JsonToken.StartArray)
            {
                numArray = this.ReadByteArray(reader);
            }
            else
            {
                if (reader.TokenType != JsonToken.String)
                {
                    throw JsonSerializationException.Create(reader,
                                                            "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(
                                                                (IFormatProvider)CultureInfo.InvariantCulture, (object)reader.TokenType));
                }
                numArray = Convert.FromBase64String(reader.Value.ToString());
            }

            if ((ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType) ==
                typeof(SqlBinary))
            {
                return((object)new SqlBinary(numArray));
            }
            throw JsonSerializationException.Create(reader,
                                                    "Unexpected object type when writing binary: {0}".FormatWith((IFormatProvider)CultureInfo.InvariantCulture,
                                                                                                                 (object)objectType));
        }
Exemple #4
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool nullable = ReflectionUtils.IsNullableType(objectType);

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return(null);
            }

            if (reader.TokenType == JsonToken.Date)
            {
                return(reader.Value);
            }

            if (reader.TokenType != JsonToken.String)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            string dateText = reader.Value.ToString();

            if (string.IsNullOrEmpty(dateText) && nullable)
            {
                return(null);
            }



            if (!string.IsNullOrEmpty(_dateTimeFormat))
            {
                return(DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles));
            }
            else
            {
                return(DateTime.Parse(dateText, Culture, _dateTimeStyles));
            }
        }
Exemple #5
0
 public override object ReadJson(JsonReader reader, Type objectType, [Nullable(2)] object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType != JsonToken.Null)
     {
         object obj  = null;
         object obj2 = null;
         reader.ReadAndAssert();
         Type             key = ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType;
         ReflectionObject reflectionObject = KeyValuePairConverter.ReflectionObjectPerType.Get(key);
         JsonContract     jsonContract     = serializer.ContractResolver.ResolveContract(reflectionObject.GetType("Key"));
         JsonContract     jsonContract2    = serializer.ContractResolver.ResolveContract(reflectionObject.GetType("Value"));
         while (reader.TokenType == JsonToken.PropertyName)
         {
             string a = reader.Value.ToString();
             if (string.Equals(a, "Key", StringComparison.OrdinalIgnoreCase))
             {
                 reader.ReadForTypeAndAssert(jsonContract, false);
                 obj = serializer.Deserialize(reader, jsonContract.UnderlyingType);
             }
             else if (string.Equals(a, "Value", StringComparison.OrdinalIgnoreCase))
             {
                 reader.ReadForTypeAndAssert(jsonContract2, false);
                 obj2 = serializer.Deserialize(reader, jsonContract2.UnderlyingType);
             }
             else
             {
                 reader.Skip();
             }
             reader.ReadAndAssert();
         }
         return(reflectionObject.Creator(new object[]
         {
             obj,
             obj2
         }));
     }
     if (!ReflectionUtils.IsNullableType(objectType))
     {
         throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
     }
     return(null);
 }
Exemple #6
0
 // Token: 0x06000998 RID: 2456 RVA: 0x0003748C File Offset: 0x0003568C
 private bool method_20(JsonWriter jsonWriter_0, object object_0, JsonContainerContract jsonContainerContract_0, JsonProperty jsonProperty_0, JsonProperty jsonProperty_1, out JsonContract jsonContract_0, out object object_1)
 {
     if (!jsonProperty_1.Ignored && jsonProperty_1.Readable && this.ShouldSerialize(jsonWriter_0, jsonProperty_1, object_0) && this.method_40(jsonWriter_0, jsonProperty_1, object_0))
     {
         if (jsonProperty_1.method_0() == null)
         {
             jsonProperty_1.method_1(this.jsonSerializer_0.icontractResolver_0.ResolveContract(jsonProperty_1.PropertyType));
         }
         object_1       = jsonProperty_1.ValueProvider.GetValue(object_0);
         jsonContract_0 = (jsonProperty_1.method_0().bool_4 ? jsonProperty_1.method_0() : this.method_7(object_1));
         if (this.method_12(object_1, jsonContainerContract_0 as JsonObjectContract, jsonProperty_1))
         {
             if (this.method_11(object_1, jsonProperty_1, jsonContract_0, jsonContainerContract_0, jsonProperty_0))
             {
                 jsonProperty_1.method_3(jsonWriter_0);
                 this.method_14(jsonWriter_0, object_1);
                 return(false);
             }
             if (!this.method_13(jsonWriter_0, object_1, jsonProperty_1, jsonContract_0, jsonContainerContract_0, jsonProperty_0))
             {
                 return(false);
             }
             if (object_1 == null)
             {
                 JsonObjectContract jsonObjectContract = jsonContainerContract_0 as JsonObjectContract;
                 Required           required           = jsonProperty_1.nullable_0 ?? (((jsonObjectContract != null) ? jsonObjectContract.ItemRequired : null) ?? Required.Default);
                 if (required == Required.Always)
                 {
                     throw JsonSerializationException.Create(null, jsonWriter_0.xEuXaafal7(), "Cannot write a null value for property '{0}'. Property requires a value.".smethod_0(CultureInfo.InvariantCulture, jsonProperty_1.PropertyName), null);
                 }
                 if (required == Required.DisallowNull)
                 {
                     throw JsonSerializationException.Create(null, jsonWriter_0.xEuXaafal7(), "Cannot write a null value for property '{0}'. Property requires a non-null value.".smethod_0(CultureInfo.InvariantCulture, jsonProperty_1.PropertyName), null);
                 }
             }
             return(true);
         }
     }
     jsonContract_0 = null;
     object_1       = null;
     return(false);
 }
        public override object ReadJson(JsonReader reader, Type objectType, [Nullable(2)] object existingValue, JsonSerializer serializer)
        {
            bool flag = ReflectionUtils.IsNullable(objectType);

            if (reader.TokenType == JsonToken.Null)
            {
                if (!flag)
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }
                return(null);
            }
            else
            {
                long num;
                if (reader.TokenType == JsonToken.Integer)
                {
                    num = (long)reader.Value;
                }
                else
                {
                    if (reader.TokenType != JsonToken.String)
                    {
                        throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer or String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                    }
                    if (!long.TryParse((string)reader.Value, out num))
                    {
                        throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                    }
                }
                if (num < 0L)
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert value that is before Unix epoch of 00:00:00 UTC on 1 January 1970 to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }
                DateTime dateTime = UnixDateTimeConverter.UnixEpoch.AddSeconds((double)num);
                if ((flag ? Nullable.GetUnderlyingType(objectType) : objectType) == typeof(DateTimeOffset))
                {
                    return(new DateTimeOffset(dateTime, TimeSpan.Zero));
                }
                return(dateTime);
            }
        }
        private object ReadValue(JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment)
            {
                if (!reader.Read())
                {
                    throw JsonSerializationException.Create(reader, "Unexpected end when reading ObjectInstance.");
                }
            }

            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
                return(ReadObject(reader));

            case JsonToken.StartArray:
                return(ReadArray(reader));

            case JsonToken.Date:
                var dateInstance = JurassicHelper.ToDateInstance(this.Engine, (DateTime)reader.Value);
                return(dateInstance);

            case JsonToken.Null:
                return(Null.Value);

            case JsonToken.Undefined:
                return(Undefined.Value);

            case JsonToken.Bytes:
                var byteArray = new Base64EncodedByteArrayInstance(this.Engine.Object.InstancePrototype, (byte[])reader.Value);
                return(byteArray);

            case JsonToken.Boolean:
            case JsonToken.Float:
            case JsonToken.Integer:
            case JsonToken.String:
                return(reader.Value);

            default:
                throw JsonSerializationException.Create(reader, "Unexpected token when converting ObjectInstance: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return(null);
            }

            bool isNullable = ReflectionUtils.IsNullableType(objectType);
            Type t          = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string enumText = reader.Value.ToString();

                    return(EnumUtils.ParseEnumName(enumText, isNullable, !AllowIntegerValues, t));
                }

                if (reader.TokenType == JsonToken.Integer)
                {
                    if (!AllowIntegerValues)
                    {
                        throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                    }

                    return(ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t));
                }
            }
            catch (Exception ex)
            {
                throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
            }

            // we don't actually expect to get here.
            throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Type type = ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }
                return(null);
            }
            else
            {
                byte[] array;
                if (reader.TokenType == JsonToken.StartArray)
                {
                    array = this.ReadByteArray(reader);
                }
                else
                {
                    if (reader.TokenType != JsonToken.String)
                    {
                        throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                    }
                    string s = reader.Value.ToString();
                    array = Convert.FromBase64String(s);
                }
                if (type.AssignableToTypeName("System.Data.Linq.Binary"))
                {
                    return(Activator.CreateInstance(type, new object[]
                    {
                        array
                    }));
                }
                if (type == typeof(SqlBinary))
                {
                    return(new SqlBinary(array));
                }
                throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
            }
        }
Exemple #11
0
        public override object Deserialize(IJsonReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.Token == JsonToken.StringLiteral)
            {
                return(Enum.Parse(this.enumType, reader.ReadString(false), true));
            }
            else if (reader.Token == JsonToken.Number)
            {
                return(Enum.ToObject(this.enumType, reader.ReadValue(this.enumBaseType, false)));
            }
            else
            {
                throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Number, JsonToken.StringLiteral);
            }
        }
        private object ReadValue(JsonReader reader)
        {
            if (!reader.MoveToContent())
            {
                throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
            }
            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
                return(this.ReadObject(reader));

            case JsonToken.StartArray:
                return(this.ReadList(reader));
            }
            if (!JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
            {
                throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
            return(reader.Value);
        }
        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);
        }
Exemple #14
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool flag = Class194.smethod_10(objectType);

            if (reader.JsonToken_0 == JsonToken.Null)
            {
                if (!flag)
                {
                    throw JsonSerializationException.smethod_1(reader, "Cannot convert null value to KeyValuePair.");
                }
                return(null);
            }
            Type         type             = flag ? Nullable.GetUnderlyingType(objectType) : objectType;
            IList <Type> genericArguments = type.GetGenericArguments();
            Type         type2            = genericArguments[0];
            Type         type3            = genericArguments[1];
            object       obj2             = null;
            object       obj3             = null;

            reader.Read();
            while (reader.JsonToken_0 == JsonToken.PropertyName)
            {
                string a = reader.Object_0.ToString();
                if (string.Equals(a, "Key", StringComparison.OrdinalIgnoreCase))
                {
                    reader.Read();
                    obj2 = serializer.Deserialize(reader, type2);
                }
                else if (string.Equals(a, "Value", StringComparison.OrdinalIgnoreCase))
                {
                    reader.Read();
                    obj3 = serializer.Deserialize(reader, type3);
                }
                else
                {
                    reader.Skip();
                }
                reader.Read();
            }
            return(Activator.CreateInstance(type, new object[] { obj2, obj3 }));
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object obj;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }
                return(null);
            }
            bool flag = ReflectionUtils.IsNullableType(objectType);
            Type type = (flag ? Nullable.GetUnderlyingType(objectType) : objectType);

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    obj = EnumUtils.ParseEnumName(reader.Value.ToString(), flag, type);
                }
                else if (reader.TokenType != JsonToken.Integer)
                {
                    throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                }
                else
                {
                    if (!this.AllowIntegerValues)
                    {
                        throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                    }
                    obj = ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, type);
                }
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), exception);
            }
            return(obj);
        }
Exemple #16
0
 public string Serialize(object obj)
 {
     //IL_0044: Expected O, but got Unknown
     try
     {
         if (jsonConverter.IsValueCreated)
         {
             jsonConverter.Value.ResetUsageInformation();
             return(JsonConvert.SerializeObject(obj, (JsonConverter[])(object)new JsonConverter[1]
             {
                 jsonConverter.Value
             }));
         }
         return(JsonConvert.SerializeObject(obj));
     }
     catch (JsonSerializationException val)
     {
         JsonSerializationException val2 = (JsonSerializationException)(object)val;
         throw new ComplexObjectSerializerException(((Exception)(object)val2).Message, (Exception)(object)val2);
     }
 }
Exemple #17
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object?ReadJson(
            JsonReader reader,
            Type objectType,
            object?existingValue,
            JsonSerializer serializer
            )
        {
            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
                return(ReadRegexObject(reader, serializer));

            case JsonToken.String:
                return(ReadRegexString(reader));

            case JsonToken.Null:
                return(null);
            }

            throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
        }
Exemple #18
0
        private object ReadRegexString(JsonReader reader)
        {
            string regexText = (string)reader.Value !;

            if (regexText.Length > 0 && regexText[0] == '/')
            {
                int patternOptionDelimiterIndex = regexText.LastIndexOf('/');

                if (patternOptionDelimiterIndex > 0)
                {
                    string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
                    string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);

                    RegexOptions options = MiscellaneousUtils.GetRegexOptions(optionsText);

                    return(new Regex(patternText, options));
                }
            }

            throw JsonSerializationException.Create(reader, "Regex pattern must be enclosed by slashes.");
        }
Exemple #19
0
        // Token: 0x060014DB RID: 5339 RVA: 0x0006EC20 File Offset: 0x0006CE20
        public override void WriteJson(JsonWriter writer, [Nullable(2)] object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }
            Enum   @enum = (Enum)value;
            string value2;

            if (EnumUtils.TryToString(@enum.GetType(), value, this.NamingStrategy, out value2))
            {
                writer.WriteValue(value2);
                return;
            }
            if (!this.AllowIntegerValues)
            {
                throw JsonSerializationException.Create(null, writer.ContainerPath, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, @enum.ToString("D")), null);
            }
            writer.WriteValue(value);
        }
Exemple #20
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);
        }
Exemple #21
0
        public MsgPackWriter(Stream stream, SerializationContext context)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (!stream.CanWrite)
            {
                throw JsonSerializationException.StreamIsNotReadable();
            }

            this.context      = context;
            this.outputStream = stream;
            this.buffer       = new byte[16];
            this.bitConverter = EndianBitConverter.Big;
            this.bytesWritten = 0;
        }
        public PrimitiveSerializer(Type primitiveType)
        {
            if (primitiveType == null)
            {
                throw new ArgumentNullException("primitiveType");
            }

            if (primitiveType.IsGenericType && primitiveType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                throw JsonSerializationException.TypeIsNotValid(typeof(PrimitiveSerializer), "can't be nullable type");
            }

            this.primitiveType     = primitiveType;
            this.primitiveTypeCode = Type.GetTypeCode(primitiveType);

            if (this.primitiveTypeCode == TypeCode.Object || this.primitiveTypeCode == TypeCode.Empty ||
                this.primitiveTypeCode == TypeCode.DBNull)
            {
                throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a primitive type");
            }
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (ReflectionUtils.IsNullableType(objectType))
     {
         Nullable.GetUnderlyingType(objectType);
     }
     if (reader.TokenType == JsonToken.Null)
     {
         if (!ReflectionUtils.IsNullable(objectType))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Cannot convert null value to {0}.", (IFormatProvider)CultureInfo.InvariantCulture, (object)objectType));
         }
         else
         {
             return((object)null);
         }
     }
     else
     {
         if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token or value when parsing date. Token: {0}, Value: {1}", (IFormatProvider)CultureInfo.InvariantCulture, (object)reader.TokenType, reader.Value));
         }
         reader.Read();
         if (reader.TokenType != JsonToken.Integer)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected Integer, got {0}.", (IFormatProvider)CultureInfo.InvariantCulture, (object)reader.TokenType));
         }
         DateTime dateTime = JsonConvert.ConvertJavaScriptTicksToDateTime((long)reader.Value);
         reader.Read();
         if (reader.TokenType != JsonToken.EndConstructor)
         {
             throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected token parsing date. Expected EndConstructor, got {0}.", (IFormatProvider)CultureInfo.InvariantCulture, (object)reader.TokenType));
         }
         else
         {
             return((object)dateTime);
         }
     }
 }
        private bool ReadToBuffer(int bytesRequired, bool throwOnEos)
        {
            this.bufferAvailable -= this.bufferRead;
            this.bufferOffset    += this.bufferRead;
            this.bufferRead       = 0;

            if (this.bufferAvailable < bytesRequired)
            {
                if (this.bufferAvailable > 0)
                {
                    Buffer.BlockCopy(this.buffer, this.bufferOffset, this.buffer, 0, this.bufferAvailable);
                }

                this.bufferOffset = 0;

                while (this.bufferAvailable < bytesRequired)
                {
                    var read = this.inputStream.Read(this.buffer, this.bufferAvailable, this.buffer.Length - this.bufferAvailable);
                    this.bufferAvailable += read;

                    if (read != 0 || this.bufferAvailable >= bytesRequired)
                    {
                        continue;
                    }

                    if (throwOnEos)
                    {
                        throw JsonSerializationException.UnexpectedEndOfStream(this);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            this.bufferRead      = bytesRequired;
            this.totalBytesRead += bytesRequired;
            return(true);
        }
        private object ReadList(JsonReader reader)
        {
            IList <object> list = new List <object>();

            while (reader.Read())
            {
                JsonToken tokenType = reader.TokenType;
                if (tokenType != JsonToken.Comment)
                {
                    if (tokenType != JsonToken.EndArray)
                    {
                        object item = this.ReadValue(reader);
                        list.Add(item);
                    }
                    else
                    {
                        return(list);
                    }
                }
            }
            throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
        }
Exemple #26
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);
        }
 protected override string ConvertEventToString(RemoteSettingsLogger.RemoteSettingsLogMessage eventData)
 {
     //IL_0001: Unknown result type (might be due to invalid IL or missing references)
     //IL_0006: Unknown result type (might be due to invalid IL or missing references)
     //IL_0012: Expected O, but got Unknown
     //IL_0016: Expected O, but got Unknown
     try
     {
         JsonSerializerSettings val = new JsonSerializerSettings();
         val.NullValueHandling = ((NullValueHandling)1);
         return(JsonConvert.SerializeObject((object)eventData, (JsonSerializerSettings)(object)val));
     }
     catch (JsonSerializationException val2)
     {
         JsonSerializationException val3 = (JsonSerializationException)(object)val2;
         return(string.Format(CultureInfo.InvariantCulture, "{{\"Name\":\"{0}\",\"Error\":\"Cannot serialize log message. Error: {1}\"}}", new object[2]
         {
             eventData.Message,
             ((Exception)(object)val3).Message
         }));
     }
 }
Exemple #28
0
        private static Type GetColumnDataType(JsonReader reader)
        {
            JsonToken tokenType = reader.TokenType;

            switch (tokenType)
            {
            case JsonToken.Integer:
            case JsonToken.Boolean:
            case JsonToken.Float:
            case JsonToken.String:
            case JsonToken.Date:
            case JsonToken.Bytes:
                return(reader.ValueType !);

            case JsonToken.Null:
            case JsonToken.Undefined:
            case JsonToken.EndArray:
                return(typeof(string));

            case JsonToken.StartArray:
                reader.ReadAndAssert();
                if (reader.TokenType == JsonToken.StartObject)
                {
                    return(typeof(DataTable));    // nested datatable
                }

                Type arrayType = GetColumnDataType(reader);
                return(arrayType.MakeArrayType());

            default:
                throw JsonSerializationException.Create(
                          reader,
                          "Unexpected JSON token when reading DataTable: {0}".FormatWith(
                              CultureInfo.InvariantCulture,
                              tokenType
                              )
                          );
            }
        }
Exemple #29
0
        private static void HumanizeJsonParseException(JsonSerializationException ex)
        {
            var m = regexJsonTypeConversionError.Match(ex.Message);

            if (m.Success)
            {
                var value = m.Groups[1].Value;
                var type  = Type.GetType(m.Groups[2].Value);
                var line  = m.Groups[3].Value;
                var col   = m.Groups[4].Value;

                if (type == typeof(PayoutScheme))
                {
                    Console.WriteLine($"Error: Payout scheme '{value}' is not (yet) supported (line {line}, column {col})");
                }
            }

            else
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
Exemple #30
0
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return((object)null);
            }
            DataTable dt = existingValue as DataTable ?? (objectType == typeof(DataTable)
                       ? new DataTable()
                       : (DataTable)Activator.CreateInstance(objectType));

            if (reader.TokenType == JsonToken.PropertyName)
            {
                dt.TableName = (string)reader.Value;
                reader.ReadAndAssert();
                if (reader.TokenType == JsonToken.Null)
                {
                    return((object)dt);
                }
            }

            if (reader.TokenType != JsonToken.StartArray)
            {
                throw JsonSerializationException.Create(reader,
                                                        "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(
                                                            (IFormatProvider)CultureInfo.InvariantCulture, (object)reader.TokenType));
            }
            reader.ReadAndAssert();
            while (reader.TokenType != JsonToken.EndArray)
            {
                DataTableConverter.CreateRow(reader, dt, serializer);
                reader.ReadAndAssert();
            }

            return((object)dt);
        }
Exemple #31
0
 public override object ReadJson(JsonReader reader, Type objectType, [Nullable(2)] object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType != JsonToken.Null)
     {
         bool flag = ReflectionUtils.IsNullableType(objectType);
         Type type = flag ? Nullable.GetUnderlyingType(objectType) : objectType;
         try
         {
             if (reader.TokenType == JsonToken.String)
             {
                 object value  = reader.Value;
                 string value2 = (value != null) ? value.ToString() : null;
                 if (StringUtils.IsNullOrEmpty(value2) && flag)
                 {
                     return(null);
                 }
                 return(EnumUtils.ParseEnum(type, this.NamingStrategy, value2, !this.AllowIntegerValues));
             }
             else if (reader.TokenType == JsonToken.Integer)
             {
                 if (!this.AllowIntegerValues)
                 {
                     throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                 }
                 return(ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, type));
             }
         }
         catch (Exception ex)
         {
             throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(reader.Value), objectType), ex);
         }
         throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
     }
     if (!ReflectionUtils.IsNullableType(objectType))
     {
         throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
     }
     return(null);
 }
Exemple #32
0
        private byte[] ReadByteArray(JsonReader reader)
        {
            List <byte> list = new List <byte>();

            while (reader.Read())
            {
                JsonToken tokenType = reader.TokenType;
                if (tokenType != JsonToken.Comment)
                {
                    if (tokenType != JsonToken.Integer)
                    {
                        if (tokenType != JsonToken.EndArray)
                        {
                            throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                        }
                        return(list.ToArray());
                    }
                    list.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
                }
            }
            throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
        }
    private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id)
    {
      OnDeserializing(reader, contract, newObject);

      // only need to keep a track of properies presence if they are required or a value should be defaulted if missing
      Dictionary<JsonProperty, PropertyPresence> propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer.DefaultValueHandling, DefaultValueHandling.Populate))
        ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None)
        : null;

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

      int initialDepth = reader.Depth;

      bool finished = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            {
              string memberName = reader.Value.ToString();

              try
              {
                // attempt exact case match first
                // then try match ignoring case
                JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

                if (property == null)
                {
                  if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null);

                  if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                    throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));

                  reader.Skip();
                  continue;
                }

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

                JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, member);

                if (!ReadForType(reader, property.PropertyContract, propertyConverter != null))
                  throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

                SetPropertyPresence(reader, property, propertiesPresence);

                SetPropertyValue(property, propertyConverter, contract, member, reader, newObject);
              }
              catch (Exception ex)
              {
	              var newEx = new JsonSerializationException("Could not read value for property: " + memberName, ex);
				  TryClearErrorContext();
	              if (IsErrorHandled(newObject, contract, memberName, reader as IJsonLineInfo, reader.Path, newEx))
		              HandleError(reader, true, initialDepth);
	              else
		              throw newEx;
              }
            }
            break;
          case JsonToken.EndObject:
            finished = true;
            break;
          case JsonToken.Comment:
            // ignore
            break;
          default:
            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!finished && reader.Read());

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

      EndObject(newObject, reader, contract, initialDepth, propertiesPresence);

      OnDeserialized(reader, contract, newObject);
      return newObject;
    }