Beispiel #1
0
 public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
 {
   if (converters != null && converters.Length > 0 && this._value != null)
   {
     JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter((IList<JsonConverter>) converters, this._value.GetType());
     if (matchingConverter != null)
     {
       matchingConverter.WriteJson(writer, this._value, new JsonSerializer());
       return;
     }
   }
   switch (this._valueType)
   {
     case JTokenType.Comment:
       writer.WriteComment(this._value != null ? this._value.ToString() : (string) null);
       break;
     case JTokenType.Integer:
       writer.WriteValue(Convert.ToInt64(this._value, (IFormatProvider) CultureInfo.InvariantCulture));
       break;
     case JTokenType.Float:
       if (this._value is Decimal)
       {
         writer.WriteValue((Decimal) this._value);
         break;
       }
       else if (this._value is double)
       {
         writer.WriteValue((double) this._value);
         break;
       }
       else if (this._value is float)
       {
         writer.WriteValue((float) this._value);
         break;
       }
       else
       {
         writer.WriteValue(Convert.ToDouble(this._value, (IFormatProvider) CultureInfo.InvariantCulture));
         break;
       }
     case JTokenType.String:
       writer.WriteValue(this._value != null ? this._value.ToString() : (string) null);
       break;
     case JTokenType.Boolean:
       writer.WriteValue(Convert.ToBoolean(this._value, (IFormatProvider) CultureInfo.InvariantCulture));
       break;
     case JTokenType.Null:
       writer.WriteNull();
       break;
     case JTokenType.Undefined:
       writer.WriteUndefined();
       break;
     case JTokenType.Date:
       writer.WriteValue(Convert.ToDateTime(this._value, (IFormatProvider) CultureInfo.InvariantCulture));
       break;
     case JTokenType.Raw:
       writer.WriteRawValue(this._value != null ? this._value.ToString() : (string) null);
       break;
     case JTokenType.Bytes:
       writer.WriteValue((byte[]) this._value);
       break;
     case JTokenType.Guid:
     case JTokenType.Uri:
     case JTokenType.TimeSpan:
       writer.WriteValue(this._value != null ? this._value.ToString() : (string) null);
       break;
     default:
       throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", (object) this._valueType, "Unexpected token type.");
   }
 }
        /// <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 isNullable = ReflectionUtils.IsNullableType(objectType);
            Type t          = isNullable ? Nullable.GetUnderlyingType(objectType) : 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);
            }

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string enumText = reader.Value.ToString();
                    if (enumText == string.Empty && isNullable)
                    {
                        return(null);
                    }

                    var    map = GetEnumNameMap(t);
                    string resolvedEnumName;
                    map.TryGetBySecond(enumText, out resolvedEnumName);
                    resolvedEnumName = resolvedEnumName ?? enumText;

                    return(Enum.Parse(t, resolvedEnumName, true));
                }

                if (reader.TokenType == JsonToken.Integer)
                {
                    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);
            }


            throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
        }
Beispiel #3
0
        /// <summary>
        /// Gets the <see cref="JToken"/> with the specified key.
        /// </summary>
        /// <value>The <see cref="JToken"/> with the specified key.</value>
        public override JToken this[object key]
        {
            get
            {
                ValidationUtils.ArgumentNotNull(key, nameof(key));

                if (!(key is int))
                {
                    throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                return(GetItem((int)key));
            }
            set
            {
                ValidationUtils.ArgumentNotNull(key, nameof(key));

                if (!(key is int))
                {
                    throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                SetItem((int)key, value);
            }
        }
Beispiel #4
0
        internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return(0);
            }
            if (objA != null && objB == null)
            {
                return(1);
            }
            if (objA == null && objB != null)
            {
                return(-1);
            }

            switch (valueType)
            {
            case JTokenType.Integer:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
                if (objA is BigInteger)
                {
                    return(CompareBigInteger((BigInteger)objA, objB));
                }
                if (objB is BigInteger)
                {
                    return(-CompareBigInteger((BigInteger)objB, objA));
                }
#endif
                if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                {
                    return(Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)));
                }
                else if (objA is float || objB is float || objA is double || objB is double)
                {
                    return(CompareFloat(objA, objB));
                }
                else
                {
                    return(Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)));
                }

            case JTokenType.Float:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
                if (objA is BigInteger)
                {
                    return(CompareBigInteger((BigInteger)objA, objB));
                }
                if (objB is BigInteger)
                {
                    return(-CompareBigInteger((BigInteger)objB, objA));
                }
#endif
                return(CompareFloat(objA, objB));

            case JTokenType.Comment:
            case JTokenType.String:
            case JTokenType.Raw:
                string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                return(string.CompareOrdinal(s1, s2));

            case JTokenType.Boolean:
                bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                return(b1.CompareTo(b2));

            case JTokenType.Date:
#if !NET20
                if (objA is DateTime)
                {
#endif
                DateTime date1 = (DateTime)objA;
                DateTime date2;

#if !NET20
                if (objB is DateTimeOffset)
                {
                    date2 = ((DateTimeOffset)objB).DateTime;
                }
                else
#endif
                {
                    date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                }

                return(date1.CompareTo(date2));

#if !NET20
            }
            else
            {
                DateTimeOffset date1 = (DateTimeOffset)objA;
                DateTimeOffset date2;

                if (objB is DateTimeOffset)
                {
                    date2 = (DateTimeOffset)objB;
                }
                else
                {
                    date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                }

                return(date1.CompareTo(date2));
            }
#endif
            case JTokenType.Bytes:
                if (!(objB is byte[]))
                {
                    throw new ArgumentException("Object must be of type byte[].");
                }

                byte[] bytes1 = objA as byte[];
                byte[] bytes2 = objB as byte[];
                if (bytes1 == null)
                {
                    return(-1);
                }
                if (bytes2 == null)
                {
                    return(1);
                }

                return(MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2));

            case JTokenType.Guid:
                if (!(objB is Guid))
                {
                    throw new ArgumentException("Object must be of type Guid.");
                }

                Guid guid1 = (Guid)objA;
                Guid guid2 = (Guid)objB;

                return(guid1.CompareTo(guid2));

            case JTokenType.Uri:
                if (!(objB is Uri))
                {
                    throw new ArgumentException("Object must be of type Uri.");
                }

                Uri uri1 = (Uri)objA;
                Uri uri2 = (Uri)objB;

                return(Comparer <string> .Default.Compare(uri1.ToString(), uri2.ToString()));

            case JTokenType.TimeSpan:
                if (!(objB is TimeSpan))
                {
                    throw new ArgumentException("Object must be of type TimeSpan.");
                }

                TimeSpan ts1 = (TimeSpan)objA;
                TimeSpan ts2 = (TimeSpan)objB;

                return(ts1.CompareTo(ts2));

            default:
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }
        internal void WriteToken(JsonReader reader, int initialDepth)
        {
            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.None:
                    // read to next
                    break;

                case JsonToken.StartObject:
                    WriteStartObject();
                    break;

                case JsonToken.StartArray:
                    WriteStartArray();
                    break;

                case JsonToken.StartConstructor:
                    string constructorName = reader.Value.ToString();
                    // write a JValue date when the constructor is for a date
                    if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0)
                    {
                        WriteConstructorDate(reader);
                    }
                    else
                    {
                        WriteStartConstructor(reader.Value.ToString());
                    }
                    break;

                case JsonToken.PropertyName:
                    WritePropertyName(reader.Value.ToString());
                    break;

                case JsonToken.Comment:
                    WriteComment(reader.Value.ToString());
                    break;

                case JsonToken.Integer:
                    WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
                    break;

                case JsonToken.Float:
                    WriteValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
                    break;

                case JsonToken.String:
                    WriteValue(reader.Value.ToString());
                    break;

                case JsonToken.Boolean:
                    WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
                    break;

                case JsonToken.Null:
                    WriteNull();
                    break;

                case JsonToken.Undefined:
                    WriteUndefined();
                    break;

                case JsonToken.EndObject:
                    WriteEndObject();
                    break;

                case JsonToken.EndArray:
                    WriteEndArray();
                    break;

                case JsonToken.EndConstructor:
                    WriteEndConstructor();
                    break;

                case JsonToken.Date:
                    WriteValue((DateTime)reader.Value);
                    break;

                case JsonToken.Raw:
                    WriteRawValue((string)reader.Value);
                    break;

                case JsonToken.Bytes:
                    WriteValue((byte[])reader.Value);
                    break;

                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
                }
            }while (
                // stop if we have reached the end of the token being read
                initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0) &&
                reader.Read());
        }
Beispiel #6
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/> asynchronously.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
        public override Task WriteToAsync(
            JsonWriter writer,
            CancellationToken cancellationToken,
            params JsonConverter[] converters
            )
        {
            if (converters != null && converters.Length > 0 && _value != null)
            {
                JsonConverter?matchingConverter = JsonSerializer.GetMatchingConverter(
                    converters,
                    _value.GetType()
                    );
                if (matchingConverter != null && matchingConverter.CanWrite)
                {
                    // TODO: Call WriteJsonAsync when it exists.
                    matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault());
                    return(AsyncUtils.CompletedTask);
                }
            }

            switch (_valueType)
            {
            case JTokenType.Comment:
                return(writer.WriteCommentAsync(_value?.ToString(), cancellationToken));

            case JTokenType.Raw:
                return(writer.WriteRawValueAsync(_value?.ToString(), cancellationToken));

            case JTokenType.Null:
                return(writer.WriteNullAsync(cancellationToken));

            case JTokenType.Undefined:
                return(writer.WriteUndefinedAsync(cancellationToken));

            case JTokenType.Integer:
                if (_value is int i)
                {
                    return(writer.WriteValueAsync(i, cancellationToken));
                }

                if (_value is long l)
                {
                    return(writer.WriteValueAsync(l, cancellationToken));
                }

                if (_value is ulong ul)
                {
                    return(writer.WriteValueAsync(ul, cancellationToken));
                }
#if HAVE_BIG_INTEGER
                if (_value is BigInteger integer)
                {
                    return(writer.WriteValueAsync(integer, cancellationToken));
                }
#endif

                return(writer.WriteValueAsync(
                           Convert.ToInt64(_value, CultureInfo.InvariantCulture),
                           cancellationToken
                           ));

            case JTokenType.Float:
                if (_value is decimal dec)
                {
                    return(writer.WriteValueAsync(dec, cancellationToken));
                }

                if (_value is double d)
                {
                    return(writer.WriteValueAsync(d, cancellationToken));
                }

                if (_value is float f)
                {
                    return(writer.WriteValueAsync(f, cancellationToken));
                }

                return(writer.WriteValueAsync(
                           Convert.ToDouble(_value, CultureInfo.InvariantCulture),
                           cancellationToken
                           ));

            case JTokenType.String:
                return(writer.WriteValueAsync(_value?.ToString(), cancellationToken));

            case JTokenType.Boolean:
                return(writer.WriteValueAsync(
                           Convert.ToBoolean(_value, CultureInfo.InvariantCulture),
                           cancellationToken
                           ));

            case JTokenType.Date:
                if (_value is DateTimeOffset offset)
                {
                    return(writer.WriteValueAsync(offset, cancellationToken));
                }

                return(writer.WriteValueAsync(
                           Convert.ToDateTime(_value, CultureInfo.InvariantCulture),
                           cancellationToken
                           ));

            case JTokenType.Bytes:
                return(writer.WriteValueAsync((byte[]?)_value, cancellationToken));

            case JTokenType.Guid:
                return(writer.WriteValueAsync(
                           _value != null ? (Guid?)_value : null,
                           cancellationToken
                           ));

            case JTokenType.TimeSpan:
                return(writer.WriteValueAsync(
                           _value != null ? (TimeSpan?)_value : null,
                           cancellationToken
                           ));

            case JTokenType.Uri:
                return(writer.WriteValueAsync((Uri?)_value, cancellationToken));
            }

            throw MiscellaneousUtils.CreateArgumentOutOfRangeException(
                      nameof(Type),
                      _valueType,
                      "Unexpected token type."
                      );
        }
Beispiel #7
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)
        {
            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();

                    if (enumText == string.Empty && isNullable)
                    {
                        return(null);
                    }

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

                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));
        }
Beispiel #8
0
 public override JToken this[object key]
 {
     get
     {
         ValidationUtils.ArgumentNotNull(key, "o");
         string index = key as string;
         if (index == null)
         {
             throw new ArgumentException(StringUtils.FormatWith("Accessed JObject values with invalid key value: {0}. Object property name expected.", (IFormatProvider)CultureInfo.InvariantCulture, (object)MiscellaneousUtils.ToString(key)));
         }
         else
         {
             return(this[index]);
         }
     }
     set
     {
         ValidationUtils.ArgumentNotNull(key, "o");
         string index = key as string;
         if (index == null)
         {
             throw new ArgumentException(StringUtils.FormatWith("Set JObject values with invalid key value: {0}. Object property name expected.", (IFormatProvider)CultureInfo.InvariantCulture, (object)MiscellaneousUtils.ToString(key)));
         }
         this[index] = value;
     }
 }
Beispiel #9
0
        internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == objB)
            {
                return 0;
            }
            if (objB == null)
            {
                return 1;
            }
            if (objA == null)
            {
                return -1;
            }

            switch (valueType)
            {
                case JTokenType.Integer:
                {
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                        return -CompareBigInteger(integerB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    else if (objA is float || objB is float || objA is double || objB is double)
                    {
                        return CompareFloat(objA, objB);
                    }
                    else
                    {
                        return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
                    }
                }
                case JTokenType.Float:
                {
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                        return -CompareBigInteger(integerB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    return CompareFloat(objA, objB);
                }
                case JTokenType.Comment:
                case JTokenType.String:
                case JTokenType.Raw:
                    string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                    string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                    return string.CompareOrdinal(s1, s2);
                case JTokenType.Boolean:
                    bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                    bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                    return b1.CompareTo(b2);
                case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
                    if (objA is DateTime dateA)
                    {
#else
                        DateTime dateA = (DateTime)objA;
#endif
                        DateTime dateB;

#if HAVE_DATE_TIME_OFFSET
                        if (objB is DateTimeOffset offsetB)
                        {
                            dateB = offsetB.DateTime;
                        }
                        else
#endif
                        {
                            dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                        }

                        return dateA.CompareTo(dateB);
#if HAVE_DATE_TIME_OFFSET
                    }
                    else
                    {
                        DateTimeOffset offsetA = (DateTimeOffset)objA;
                        if (!(objB is DateTimeOffset offsetB))
                        {
                            offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return offsetA.CompareTo(offsetB);
                    }
#endif
                case JTokenType.Bytes:
                    if (!(objB is byte[] bytesB))
                    {
                        throw new ArgumentException("Object must be of type byte[].");
                    }

                    byte[] bytesA = objA as byte[];
                    Debug.Assert(bytesA != null);

                    return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB);
                case JTokenType.Guid:
                    if (!(objB is Guid))
                    {
                        throw new ArgumentException("Object must be of type Guid.");
                    }

                    Guid guid1 = (Guid)objA;
                    Guid guid2 = (Guid)objB;

                    return guid1.CompareTo(guid2);
                case JTokenType.Uri:
                    Uri uri2 = objB as Uri;
                    if (uri2 == null)
                    {
                        throw new ArgumentException("Object must be of type Uri.");
                    }

                    Uri uri1 = (Uri)objA;

                    return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
                case JTokenType.TimeSpan:
                    if (!(objB is TimeSpan))
                    {
                        throw new ArgumentException("Object must be of type TimeSpan.");
                    }

                    TimeSpan ts1 = (TimeSpan)objA;
                    TimeSpan ts2 = (TimeSpan)objB;

                    return ts1.CompareTo(ts2);
                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }
Beispiel #10
0
 public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
 {
     return(new XAttributeWrapper(new XAttribute(XName.Get(MiscellaneousUtils.GetLocalName(qualifiedName), namespaceUri), value)));
 }
Beispiel #11
0
 public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
 {
     return(new XElementWrapper(new XElement(XName.Get(MiscellaneousUtils.GetLocalName(qualifiedName), namespaceUri))));
 }
        public void WriteValues()
        {
            byte[]       data   = MiscellaneousUtils.HexToBytes("8C-00-00-00-12-30-00-FF-FF-FF-FF-FF-FF-FF-7F-12-31-00-FF-FF-FF-FF-FF-FF-FF-7F-10-32-00-FF-FF-FF-7F-10-33-00-FF-FF-FF-7F-10-34-00-FF-00-00-00-10-35-00-7F-00-00-00-02-36-00-02-00-00-00-61-00-01-37-00-00-00-00-00-00-00-F0-45-01-38-00-FF-FF-FF-FF-FF-FF-EF-7F-01-39-00-00-00-00-E0-FF-FF-EF-47-08-31-30-00-01-05-31-31-00-05-00-00-00-02-00-01-02-03-04-09-31-32-00-40-C5-E2-BA-E3-00-00-00-09-31-33-00-40-C5-E2-BA-E3-00-00-00-00");
            MemoryStream ms     = new MemoryStream(data);
            BsonReader   reader = new BsonReader(ms);

            reader.ReadRootValueAsArray = true;
            reader.DateTimeKindHandling = DateTimeKind.Utc;

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(long.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(long.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(int.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(int.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(byte.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Integer, reader.TokenType);
            Assert.AreEqual(sbyte.MaxValue, reader.Value);
            Assert.AreEqual(typeof(long), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.String, reader.TokenType);
            Assert.AreEqual("a", reader.Value);
            Assert.AreEqual(typeof(string), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(decimal.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(double.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Float, reader.TokenType);
            Assert.AreEqual(float.MaxValue, reader.Value);
            Assert.AreEqual(typeof(double), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
            Assert.AreEqual(true, reader.Value);
            Assert.AreEqual(typeof(bool), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
            Assert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, reader.Value);
            Assert.AreEqual(typeof(byte[]), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Date, reader.TokenType);
            Assert.AreEqual(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.Date, reader.TokenType);
            Assert.AreEqual(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc), reader.Value);
            Assert.AreEqual(typeof(DateTime), reader.ValueType);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(JsonToken.EndArray, reader.TokenType);

            Assert.IsFalse(reader.Read());
        }
 private bool ShouldWriteDynamicProperty(object memberValue)
 {
     return((this.Serializer._nullValueHandling != NullValueHandling.Ignore || memberValue != null) && (!this.HasFlag(this.Serializer._defaultValueHandling, DefaultValueHandling.Ignore) || memberValue != null && !MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))));
 }
Beispiel #14
0
 public override JToken this[object key]
 {
     get
     {
         ValidationUtils.ArgumentNotNull(key, "key");
         if (!(key is int))
         {
             throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Int32 array index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
         }
         return(this.GetItem((int)key));
     }
     set
     {
         ValidationUtils.ArgumentNotNull(key, "key");
         if (!(key is int))
         {
             throw new ArgumentException("Set JArray values with invalid key value: {0}. Int32 array index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
         }
         this.SetItem((int)key, value);
     }
 }
Beispiel #15
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 isNullable = ReflectionUtils.IsNullableType(objectType);
            Type t          = isNullable ? Nullable.GetUnderlyingType(objectType) : 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);
            }

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string enumText = reader.Value.ToString();
                    if (enumText == string.Empty && isNullable)
                    {
                        return(null);
                    }

                    string finalEnumText;

                    BidirectionalDictionary <string, string> map = GetEnumNameMap(t);
                    if (enumText.IndexOf(',') != -1)
                    {
                        string[] names = enumText.Split(',');
                        for (int i = 0; i < names.Length; i++)
                        {
                            string name = names[i].Trim();

                            names[i] = ResolvedEnumName(map, name);
                        }

                        finalEnumText = string.Join(", ", names);
                    }
                    else
                    {
                        finalEnumText = ResolvedEnumName(map, enumText);
                    }

                    return(Enum.Parse(t, finalEnumText, true));
                }

                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));
        }
        /// <summary>
        /// Adds a <see cref="JsonProperty"/> object.
        /// </summary>
        /// <param name="property">The property to add to the collection.</param>
        public void AddProperty(JsonProperty property)
        {
            MiscellaneousUtils.Assert(property.PropertyName != null);

            if (Contains(property.PropertyName))
            {
                // don't overwrite existing property with ignored property
                if (property.Ignored)
                {
                    return;
                }

                JsonProperty existingProperty  = this[property.PropertyName];
                bool         duplicateProperty = true;

                if (existingProperty.Ignored)
                {
                    // remove ignored property so it can be replaced in collection
                    Remove(existingProperty);
                    duplicateProperty = false;
                }
                else
                {
                    if (property.DeclaringType != null && existingProperty.DeclaringType != null)
                    {
                        if (
                            property.DeclaringType.IsSubclassOf(existingProperty.DeclaringType) ||
                            (
                                existingProperty.DeclaringType.IsInterface() &&
                                property.DeclaringType.ImplementInterface(
                                    existingProperty.DeclaringType
                                    )
                            )
                            )
                        {
                            // current property is on a derived class and hides the existing
                            Remove(existingProperty);
                            duplicateProperty = false;
                        }
                        if (
                            existingProperty.DeclaringType.IsSubclassOf(property.DeclaringType) ||
                            (
                                property.DeclaringType.IsInterface() &&
                                existingProperty.DeclaringType.ImplementInterface(
                                    property.DeclaringType
                                    )
                            )
                            )
                        {
                            // current property is hidden by the existing so don't add it
                            return;
                        }

                        if (
                            _type.ImplementInterface(existingProperty.DeclaringType) &&
                            _type.ImplementInterface(property.DeclaringType)
                            )
                        {
                            // current property was already defined on another interface
                            return;
                        }
                    }
                }

                if (duplicateProperty)
                {
                    throw new JsonSerializationException(
                              "A member with the name '{0}' already exists on '{1}'. Use the JsonPropertyAttribute to specify another name.".FormatWith(
                                  CultureInfo.InvariantCulture,
                                  property.PropertyName,
                                  _type
                                  )
                              );
                }
            }

            Add(property);
        }
Beispiel #17
0
 private bool ShouldWriteProperty(object memberValue, JsonProperty property)
 {
     return((property.NullValueHandling.GetValueOrDefault(this.Serializer.NullValueHandling) != NullValueHandling.Ignore || memberValue != null) && (!this.HasFlag(property.DefaultValueHandling.GetValueOrDefault(this.Serializer.DefaultValueHandling), DefaultValueHandling.Ignore) || !MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())));
 }
        internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            DateTime       dateTime;
            DateTimeOffset dateTimeOffset;

            if (objA == null && objB == null)
            {
                return(0);
            }
            if (objA != null && objB == null)
            {
                return(1);
            }
            if (objA == null && objB != null)
            {
                return(-1);
            }
            switch (valueType)
            {
            case JTokenType.Comment:
            case JTokenType.String:
            case JTokenType.Raw:
            {
                string str  = Convert.ToString(objA, CultureInfo.InvariantCulture);
                string str1 = Convert.ToString(objB, CultureInfo.InvariantCulture);
                return(string.CompareOrdinal(str, str1));
            }

            case JTokenType.Integer:
            {
                if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                {
                    decimal num = Convert.ToDecimal(objA, CultureInfo.InvariantCulture);
                    return(num.CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)));
                }
                if (objA is float || objB is float || objA is double || objB is double)
                {
                    return(JValue.CompareFloat(objA, objB));
                }
                long num1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture);
                return(num1.CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)));
            }

            case JTokenType.Float:
            {
                return(JValue.CompareFloat(objA, objB));
            }

            case JTokenType.Boolean:
            {
                bool flag  = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                bool flag1 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
                return(flag.CompareTo(flag1));
            }

            case JTokenType.Null:
            case JTokenType.Undefined:
            {
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }

            case JTokenType.Date:
            {
                if (!(objA is DateTime))
                {
                    DateTimeOffset dateTimeOffset1 = (DateTimeOffset)objA;
                    dateTimeOffset = (!(objB is DateTimeOffset) ? new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)) : (DateTimeOffset)objB);
                    return(dateTimeOffset1.CompareTo(dateTimeOffset));
                }
                DateTime dateTime1 = (DateTime)objA;
                dateTime = (!(objB is DateTimeOffset) ? Convert.ToDateTime(objB, CultureInfo.InvariantCulture) : ((DateTimeOffset)objB).DateTime);
                return(dateTime1.CompareTo(dateTime));
            }

            case JTokenType.Bytes:
            {
                if (!(objB is byte[]))
                {
                    throw new ArgumentException("Object must be of type byte[].");
                }
                byte[] numArray  = objA as byte[];
                byte[] numArray1 = objB as byte[];
                if (numArray == null)
                {
                    return(-1);
                }
                if (numArray1 == null)
                {
                    return(1);
                }
                return(MiscellaneousUtils.ByteArrayCompare(numArray, numArray1));
            }

            case JTokenType.Guid:
            {
                if (!(objB is Guid))
                {
                    throw new ArgumentException("Object must be of type Guid.");
                }
                return(((Guid)objA).CompareTo((Guid)objB));
            }

            case JTokenType.Uri:
            {
                if (!(objB is Uri))
                {
                    throw new ArgumentException("Object must be of type Uri.");
                }
                Uri uri  = (Uri)objA;
                Uri uri1 = (Uri)objB;
                return(Comparer <string> .Default.Compare(uri.ToString(), uri1.ToString()));
            }

            case JTokenType.TimeSpan:
            {
                if (!(objB is TimeSpan))
                {
                    throw new ArgumentException("Object must be of type TimeSpan.");
                }
                return(((TimeSpan)objA).CompareTo((TimeSpan)objB));
            }

            default:
            {
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
            }
        }
#pragma warning restore 108

        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
        {
            switch (_valueType)
            {
            case JTokenType.Comment:
                writer.WriteComment(_value.ToString());
                return;

            case JTokenType.Raw:
                writer.WriteRawValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Null:
                writer.WriteNull();
                return;

            case JTokenType.Undefined:
                writer.WriteUndefined();
                return;
            }

            JsonConverter matchingConverter;

            if (_value != null && ((matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType())) != null))
            {
                matchingConverter.WriteJson(writer, _value, new JsonSerializer());
                return;
            }

            switch (_valueType)
            {
            case JTokenType.Integer:
                writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Float:
                writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.String:
                writer.WriteValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Boolean:
                writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Date:
                if (_value is DateTimeOffset)
                {
                    writer.WriteValue((DateTimeOffset)_value);
                }
                else
                {
                    writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture));
                };
                return;

            case JTokenType.Bytes:
                writer.WriteValue((byte[])_value);
                return;

            case JTokenType.Guid:
            case JTokenType.Uri:
            case JTokenType.TimeSpan:
                writer.WriteValue((_value != null) ? _value.ToString() : null);
                return;
            }

            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type.");
        }
        public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
        {
            string   str;
            string   str1;
            string   str2;
            Guid?    nullable;
            TimeSpan?nullable1;

            if (converters != null && converters.Length != 0 && this._value != null)
            {
                JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, this._value.GetType());
                if (matchingConverter != null && matchingConverter.CanWrite)
                {
                    matchingConverter.WriteJson(writer, this._value, JsonSerializer.CreateDefault());
                    return;
                }
            }
            switch (this._valueType)
            {
            case JTokenType.Comment:
            {
                JsonWriter jsonWriter = writer;
                if (this._value != null)
                {
                    str = this._value.ToString();
                }
                else
                {
                    str = null;
                }
                jsonWriter.WriteComment(str);
                return;
            }

            case JTokenType.Integer:
            {
                if (this._value is int)
                {
                    writer.WriteValue((int)this._value);
                    return;
                }
                if (this._value is long)
                {
                    writer.WriteValue((long)this._value);
                    return;
                }
                if (this._value is ulong)
                {
                    writer.WriteValue((ulong)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToInt64(this._value, CultureInfo.InvariantCulture));
                return;
            }

            case JTokenType.Float:
            {
                if (this._value is decimal)
                {
                    writer.WriteValue((decimal)this._value);
                    return;
                }
                if (this._value is double)
                {
                    writer.WriteValue((double)this._value);
                    return;
                }
                if (this._value is float)
                {
                    writer.WriteValue((float)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToDouble(this._value, CultureInfo.InvariantCulture));
                return;
            }

            case JTokenType.String:
            {
                JsonWriter jsonWriter1 = writer;
                if (this._value != null)
                {
                    str1 = this._value.ToString();
                }
                else
                {
                    str1 = null;
                }
                jsonWriter1.WriteValue(str1);
                return;
            }

            case JTokenType.Boolean:
            {
                writer.WriteValue(Convert.ToBoolean(this._value, CultureInfo.InvariantCulture));
                return;
            }

            case JTokenType.Null:
            {
                writer.WriteNull();
                return;
            }

            case JTokenType.Undefined:
            {
                writer.WriteUndefined();
                return;
            }

            case JTokenType.Date:
            {
                if (this._value is DateTimeOffset)
                {
                    writer.WriteValue((DateTimeOffset)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToDateTime(this._value, CultureInfo.InvariantCulture));
                return;
            }

            case JTokenType.Raw:
            {
                JsonWriter jsonWriter2 = writer;
                if (this._value != null)
                {
                    str2 = this._value.ToString();
                }
                else
                {
                    str2 = null;
                }
                jsonWriter2.WriteRawValue(str2);
                return;
            }

            case JTokenType.Bytes:
            {
                writer.WriteValue((byte[])this._value);
                return;
            }

            case JTokenType.Guid:
            {
                JsonWriter jsonWriter3 = writer;
                if (this._value != null)
                {
                    nullable = (Guid?)this._value;
                }
                else
                {
                    nullable = null;
                }
                jsonWriter3.WriteValue(nullable);
                return;
            }

            case JTokenType.Uri:
            {
                writer.WriteValue((Uri)this._value);
                return;
            }

            case JTokenType.TimeSpan:
            {
                JsonWriter jsonWriter4 = writer;
                if (this._value != null)
                {
                    nullable1 = (TimeSpan?)this._value;
                }
                else
                {
                    nullable1 = null;
                }
                jsonWriter4.WriteValue(nullable1);
                return;
            }
            }
            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", this._valueType, "Unexpected token type.");
        }
Beispiel #21
0
        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);
            bool flag1 = flag;
            Type type  = (flag ? Nullable.GetUnderlyingType(objectType) : objectType);

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string str = reader.Value.ToString();
                    obj = (!((str == string.Empty) & flag1) ? EnumUtils.ParseEnum(type, this.NamingStrategy, str, !this.AllowIntegerValues) : null);
                }
                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.ToString(reader.Value), objectType), exception);
            }
            return(obj);
        }
Beispiel #22
0
        private void SetToken(JToken token)
        {
            switch (token.Type)
            {
            case JTokenType.Object:
                base.SetToken(JsonToken.StartObject);
                return;

            case JTokenType.Array:
                base.SetToken(JsonToken.StartArray);
                return;

            case JTokenType.Constructor:
                base.SetToken(JsonToken.StartConstructor, ((JConstructor)token).Name);
                return;

            case JTokenType.Property:
                base.SetToken(JsonToken.PropertyName, ((JProperty)token).Name);
                return;

            case JTokenType.Comment:
                base.SetToken(JsonToken.Comment, ((JValue)token).Value);
                return;

            case JTokenType.Integer:
                base.SetToken(JsonToken.Integer, ((JValue)token).Value);
                return;

            case JTokenType.Float:
                base.SetToken(JsonToken.Float, ((JValue)token).Value);
                return;

            case JTokenType.String:
                base.SetToken(JsonToken.String, ((JValue)token).Value);
                return;

            case JTokenType.Boolean:
                base.SetToken(JsonToken.Boolean, ((JValue)token).Value);
                return;

            case JTokenType.Null:
                base.SetToken(JsonToken.Null, ((JValue)token).Value);
                return;

            case JTokenType.Undefined:
                base.SetToken(JsonToken.Undefined, ((JValue)token).Value);
                return;

            case JTokenType.Date:
                base.SetToken(JsonToken.Date, ((JValue)token).Value);
                return;

            case JTokenType.Raw:
                base.SetToken(JsonToken.Raw, ((JValue)token).Value);
                return;

            case JTokenType.Bytes:
                base.SetToken(JsonToken.Bytes, ((JValue)token).Value);
                return;

            case JTokenType.Guid:
                base.SetToken(JsonToken.String, this.SafeToString(((JValue)token).Value));
                return;

            case JTokenType.Uri:
            {
                object obj2 = ((JValue)token).Value;
                if (!(obj2 is Uri))
                {
                    base.SetToken(JsonToken.String, this.SafeToString(obj2));
                    return;
                }
                base.SetToken(JsonToken.String, ((Uri)obj2).OriginalString);
                return;
            }

            case JTokenType.TimeSpan:
                base.SetToken(JsonToken.String, this.SafeToString(((JValue)token).Value));
                return;
            }
            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType.");
        }
Beispiel #23
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
        {
            if (converters != null && converters.Length > 0 && _value != null)
            {
                JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
                if (matchingConverter != null && matchingConverter.CanWrite)
                {
                    matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault());
                    return;
                }
            }

            switch (_valueType)
            {
            case JTokenType.Comment:
                writer.WriteComment((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Raw:
                writer.WriteRawValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Null:
                writer.WriteNull();
                return;

            case JTokenType.Undefined:
                writer.WriteUndefined();
                return;

            case JTokenType.Integer:
                if (_value is int)
                {
                    writer.WriteValue((int)_value);
                }
                else if (_value is long)
                {
                    writer.WriteValue((long)_value);
                }
                else if (_value is ulong)
                {
                    writer.WriteValue((ulong)_value);
                }
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
                else if (_value is BigInteger)
                {
                    writer.WriteValue((BigInteger)_value);
                }
#endif
                else
                {
                    writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
                }
                return;

            case JTokenType.Float:
                if (_value is decimal)
                {
                    writer.WriteValue((decimal)_value);
                }
                else if (_value is double)
                {
                    writer.WriteValue((double)_value);
                }
                else if (_value is float)
                {
                    writer.WriteValue((float)_value);
                }
                else
                {
                    writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
                }
                return;

            case JTokenType.String:
                writer.WriteValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Boolean:
                writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Date:
#if !NET20
                if (_value is DateTimeOffset)
                {
                    writer.WriteValue((DateTimeOffset)_value);
                }
                else
#endif
                {
                    writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture));
                }
                return;

            case JTokenType.Bytes:
                writer.WriteValue((byte[])_value);
                return;

            case JTokenType.Guid:
                writer.WriteValue((_value != null) ? (Guid?)_value : null);
                return;

            case JTokenType.TimeSpan:
                writer.WriteValue((_value != null) ? (TimeSpan?)_value : null);
                return;

            case JTokenType.Uri:
                writer.WriteValue((Uri)_value);
                return;
            }

            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type.");
        }
Beispiel #24
0
        internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return(0);
            }
            if (objA != null && objB == null)
            {
                return(1);
            }
            if (objA == null && objB != null)
            {
                return(-1);
            }
            switch (valueType)
            {
            case JTokenType.Comment:
            case JTokenType.String:
            case JTokenType.Raw:
            {
                string strA = Convert.ToString(objA, CultureInfo.InvariantCulture);
                string strB = Convert.ToString(objB, CultureInfo.InvariantCulture);
                return(string.CompareOrdinal(strA, strB));
            }

            case JTokenType.Integer:
                if (objA is BigInteger)
                {
                    return(JValue.CompareBigInteger((BigInteger)objA, objB));
                }
                if (objB is BigInteger)
                {
                    return(-JValue.CompareBigInteger((BigInteger)objB, objA));
                }
                if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                {
                    return(Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)));
                }
                if (objA is float || objB is float || objA is double || objB is double)
                {
                    return(JValue.CompareFloat(objA, objB));
                }
                return(Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)));

            case JTokenType.Float:
                if (objA is BigInteger)
                {
                    return(JValue.CompareBigInteger((BigInteger)objA, objB));
                }
                if (objB is BigInteger)
                {
                    return(-JValue.CompareBigInteger((BigInteger)objB, objA));
                }
                return(JValue.CompareFloat(objA, objB));

            case JTokenType.Boolean:
            {
                bool flag  = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                bool value = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
                return(flag.CompareTo(value));
            }

            case JTokenType.Date:
            {
                if (objA is DateTime)
                {
                    DateTime dateTime = (DateTime)objA;
                    DateTime value2;
                    if (objB is DateTimeOffset)
                    {
                        value2 = ((DateTimeOffset)objB).DateTime;
                    }
                    else
                    {
                        value2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                    }
                    return(dateTime.CompareTo(value2));
                }
                DateTimeOffset dateTimeOffset = (DateTimeOffset)objA;
                DateTimeOffset other;
                if (objB is DateTimeOffset)
                {
                    other = (DateTimeOffset)objB;
                }
                else
                {
                    other = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                }
                return(dateTimeOffset.CompareTo(other));
            }

            case JTokenType.Bytes:
            {
                if (!(objB is byte[]))
                {
                    throw new ArgumentException("Object must be of type byte[].");
                }
                byte[] array  = objA as byte[];
                byte[] array2 = objB as byte[];
                if (array == null)
                {
                    return(-1);
                }
                if (array2 == null)
                {
                    return(1);
                }
                return(MiscellaneousUtils.ByteArrayCompare(array, array2));
            }

            case JTokenType.Guid:
            {
                if (!(objB is Guid))
                {
                    throw new ArgumentException("Object must be of type Guid.");
                }
                Guid guid   = (Guid)objA;
                Guid value3 = (Guid)objB;
                return(guid.CompareTo(value3));
            }

            case JTokenType.Uri:
            {
                if (!(objB is Uri))
                {
                    throw new ArgumentException("Object must be of type Uri.");
                }
                Uri uri  = (Uri)objA;
                Uri uri2 = (Uri)objB;
                return(Comparer <string> .Default.Compare(uri.ToString(), uri2.ToString()));
            }

            case JTokenType.TimeSpan:
            {
                if (!(objB is TimeSpan))
                {
                    throw new ArgumentException("Object must be of type TimeSpan.");
                }
                TimeSpan timeSpan = (TimeSpan)objA;
                TimeSpan value4   = (TimeSpan)objB;
                return(timeSpan.CompareTo(value4));
            }
            }
            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
        }
        private void WriteMemberInfoProperty(JsonWriter writer, object memberValue, JsonProperty property, JsonContract contract)
        {
            string propertyName = property.PropertyName;
            object defaultValue = property.DefaultValue;

            if (property.NullValueHandling.GetValueOrDefault(base.Serializer.NullValueHandling) == NullValueHandling.Ignore && memberValue == null)
            {
                return;
            }
            if (this.HasFlag(property.DefaultValueHandling.GetValueOrDefault(base.Serializer.DefaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, defaultValue))
            {
                return;
            }
            if (this.ShouldWriteReference(memberValue, property, contract))
            {
                writer.WritePropertyName(propertyName);
                this.WriteReference(writer, memberValue);
                return;
            }
            if (!this.CheckForCircularReference(memberValue, property.ReferenceLoopHandling, contract))
            {
                return;
            }
            if (memberValue == null && property.Required == Required.Always)
            {
                throw new JsonSerializationException("Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, new object[]
                {
                    property.PropertyName
                }));
            }
            writer.WritePropertyName(propertyName);
            this.SerializeValue(writer, memberValue, contract, property, null);
        }
Beispiel #26
0
        public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
        {
            if (converters != null && converters.Length > 0 && this._value != null)
            {
                JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, this._value.GetType());
                if (matchingConverter != null && matchingConverter.CanWrite)
                {
                    matchingConverter.WriteJson(writer, this._value, JsonSerializer.CreateDefault());
                    return;
                }
            }
            switch (this._valueType)
            {
            case JTokenType.Comment:
                writer.WriteComment((this._value != null) ? this._value.ToString() : null);
                return;

            case JTokenType.Integer:
                if (this._value is BigInteger)
                {
                    writer.WriteValue((BigInteger)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToInt64(this._value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Float:
                if (this._value is decimal)
                {
                    writer.WriteValue((decimal)this._value);
                    return;
                }
                if (this._value is double)
                {
                    writer.WriteValue((double)this._value);
                    return;
                }
                if (this._value is float)
                {
                    writer.WriteValue((float)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToDouble(this._value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.String:
                writer.WriteValue((this._value != null) ? this._value.ToString() : null);
                return;

            case JTokenType.Boolean:
                writer.WriteValue(Convert.ToBoolean(this._value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Null:
                writer.WriteNull();
                return;

            case JTokenType.Undefined:
                writer.WriteUndefined();
                return;

            case JTokenType.Date:
                if (this._value is DateTimeOffset)
                {
                    writer.WriteValue((DateTimeOffset)this._value);
                    return;
                }
                writer.WriteValue(Convert.ToDateTime(this._value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Raw:
                writer.WriteRawValue((this._value != null) ? this._value.ToString() : null);
                return;

            case JTokenType.Bytes:
                writer.WriteValue((byte[])this._value);
                return;

            case JTokenType.Guid:
            case JTokenType.Uri:
            case JTokenType.TimeSpan:
                writer.WriteValue((this._value != null) ? this._value.ToString() : null);
                return;

            default:
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", this._valueType, "Unexpected token type.");
            }
        }
Beispiel #27
0
        /// <summary>
        /// Gets the <see cref="JToken"/> with the specified key.
        /// </summary>
        /// <value>The <see cref="JToken"/> with the specified key.</value>
        public override JToken this[object key]
        {
            get
            {
                ValidationUtils.ArgumentNotNull(key, "o");

                string propertyName = key as string;
                if (propertyName == null)
                {
                    throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                return(this[propertyName]);
            }
            set
            {
                ValidationUtils.ArgumentNotNull(key, "o");

                string propertyName = key as string;
                if (propertyName == null)
                {
                    throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
                }

                this[propertyName] = value;
            }
        }
Beispiel #28
0
        private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
            }

            Dictionary <string, string> attributeNameValues = ReadAttributeElements(reader, manager);

            string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);

            IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);

            currentNode.AppendChild(element);

            // add attributes to newly created element
            foreach (KeyValuePair <string, string> nameValue in attributeNameValues)
            {
                string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);

                IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
                               ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
                               : document.CreateAttribute(nameValue.Key, nameValue.Value);

                element.SetAttributeNode(attribute);
            }

            if (reader.TokenType == JsonToken.String)
            {
                element.AppendChild(document.CreateTextNode(reader.Value.ToString()));
            }
            else if (reader.TokenType == JsonToken.Integer)
            {
                element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Float)
            {
                element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Boolean)
            {
                element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Date)
            {
                DateTime d = (DateTime)reader.Value;
                element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind))));
            }
            else if (reader.TokenType == JsonToken.Null)
            {
                // empty element. do nothing
            }
            else
            {
                // finished element will have no children to deserialize
                if (reader.TokenType != JsonToken.EndObject)
                {
                    manager.PushScope();

                    DeserializeNode(reader, document, manager, element);

                    manager.PopScope();
                }
            }
        }
        private void SetToken(JToken token)
        {
            switch (token.Type)
            {
            case JTokenType.Object:
                SetToken(JsonToken.StartObject);
                break;

            case JTokenType.Array:
                SetToken(JsonToken.StartArray);
                break;

            case JTokenType.Constructor:
                SetToken(JsonToken.StartConstructor);
                break;

            case JTokenType.Property:
                SetToken(JsonToken.PropertyName, ((JProperty)token).Name);
                break;

            case JTokenType.Comment:
                SetToken(JsonToken.Comment, ((JValue)token).Value);
                break;

            case JTokenType.Integer:
                SetToken(JsonToken.Integer, ((JValue)token).Value);
                break;

            case JTokenType.Float:
                SetToken(JsonToken.Float, ((JValue)token).Value);
                break;

            case JTokenType.String:
                SetToken(JsonToken.String, ((JValue)token).Value);
                break;

            case JTokenType.Boolean:
                SetToken(JsonToken.Boolean, ((JValue)token).Value);
                break;

            case JTokenType.Null:
                SetToken(JsonToken.Null, ((JValue)token).Value);
                break;

            case JTokenType.Undefined:
                SetToken(JsonToken.Undefined, ((JValue)token).Value);
                break;

            case JTokenType.Date:
                SetToken(JsonToken.Date, ((JValue)token).Value);
                break;

            case JTokenType.Raw:
                SetToken(JsonToken.Raw, ((JValue)token).Value);
                break;

            case JTokenType.Bytes:
                SetToken(JsonToken.Bytes, ((JValue)token).Value);
                break;

            case JTokenType.Guid:
                SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
                break;

            case JTokenType.Uri:
                SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
                break;

            case JTokenType.TimeSpan:
                SetToken(JsonToken.String, SafeToString(((JValue)token).Value));
                break;

            default:
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType.");
            }
        }
Beispiel #30
0
        private static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return(0);
            }
            if (objA != null && objB == null)
            {
                return(1);
            }
            if (objA == null && objB != null)
            {
                return(-1);
            }

            switch (valueType)
            {
            case JTokenType.Integer:
                if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                {
                    return(Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)));
                }
                else if (objA is float || objB is float || objA is double || objB is double)
                {
                    return(CompareFloat(objA, objB));
                }
                else
                {
                    return(Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)));
                }

            case JTokenType.Float:
                return(CompareFloat(objA, objB));

            case JTokenType.Comment:
            case JTokenType.String:
            case JTokenType.Raw:
                string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                return(s1.CompareTo(s2));

            case JTokenType.Boolean:
                bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                return(b1.CompareTo(b2));

            case JTokenType.Date:
                if (objA is DateTime)
                {
                    DateTime date1 = Convert.ToDateTime(objA, CultureInfo.InvariantCulture);
                    DateTime date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);

                    return(date1.CompareTo(date2));
                }
                else
                {
                    if (!(objB is DateTimeOffset))
                    {
                        throw new ArgumentException("Object must be of type DateTimeOffset.");
                    }

                    DateTimeOffset date1 = (DateTimeOffset)objA;
                    DateTimeOffset date2 = (DateTimeOffset)objB;

                    return(date1.CompareTo(date2));
                }

            case JTokenType.Bytes:
                if (!(objB is byte[]))
                {
                    throw new ArgumentException("Object must be of type byte[].");
                }

                byte[] bytes1 = objA as byte[];
                byte[] bytes2 = objB as byte[];
                if (bytes1 == null)
                {
                    return(-1);
                }
                if (bytes2 == null)
                {
                    return(1);
                }

                return(MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2));

            case JTokenType.Guid:
                if (!(objB is Guid))
                {
                    throw new ArgumentException("Object must be of type Guid.");
                }

                Guid guid1 = (Guid)objA;
                Guid guid2 = (Guid)objB;

                return(guid1.CompareTo(guid2));

            case JTokenType.SerializableGuid:
                if (!(objB is SerializableGuid))
                {
                    throw new ArgumentException("Object must be of type Guid.");
                }

                SerializableGuid sguid1 = (SerializableGuid)objA;
                SerializableGuid sguid2 = (SerializableGuid)objB;

                return(sguid1.GetString().CompareTo(sguid2.GetString()));

            case JTokenType.Uri:
                if (!(objB is Uri))
                {
                    throw new ArgumentException("Object must be of type Uri.");
                }

                Uri uri1 = (Uri)objA;
                Uri uri2 = (Uri)objB;

                return(Comparer <string> .Default.Compare(uri1.ToString(), uri2.ToString()));

            case JTokenType.TimeSpan:
                if (!(objB is TimeSpan))
                {
                    throw new ArgumentException("Object must be of type TimeSpan.");
                }

                TimeSpan ts1 = (TimeSpan)objA;
                TimeSpan ts2 = (TimeSpan)objB;

                return(ts1.CompareTo(ts2));

            default:
                throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }