Esempio n. 1
0
 internal JsonReaderException CreateUnexpectedEndException()
 {
     return(JsonReaderException.Create(this, "Unexpected end when reading JSON."));
 }
Esempio n. 2
0
        /// <summary>
        /// Reads the next JSON token from the source as a <see cref="Byte"/>[].
        /// </summary>
        /// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
        public virtual byte[] ReadAsBytes()
        {
            JsonToken t = GetContentToken();

            switch (t)
            {
            case JsonToken.StartObject:
            {
                ReadIntoWrappedTypeObject();

                byte[] data = ReadAsBytes();
                ReaderReadAndAssert();

                if (TokenType != JsonToken.EndObject)
                {
                    throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
                }

                SetToken(JsonToken.Bytes, data, false);
                return(data);
            }

            case JsonToken.String:
            {
                // attempt to convert possible base 64 or GUID string to bytes
                // GUID has to have format 00000000-0000-0000-0000-000000000000
                string s = (string)Value;

                byte[] data;

                Guid g;
                if (s.Length == 0)
                {
                    data = CollectionUtils.ArrayEmpty <byte>();
                }
                else if (ConvertUtils.TryConvertGuid(s, out g))
                {
                    data = g.ToByteArray();
                }
                else
                {
                    data = Convert.FromBase64String(s);
                }

                SetToken(JsonToken.Bytes, data, false);
                return(data);
            }

            case JsonToken.None:
            case JsonToken.Null:
            case JsonToken.EndArray:
                return(null);

            case JsonToken.Bytes:
                if (ValueType == typeof(Guid))
                {
                    byte[] data = ((Guid)Value).ToByteArray();
                    SetToken(JsonToken.Bytes, data, false);
                    return(data);
                }

                return((byte[])Value);

            case JsonToken.StartArray:
                return(ReadArrayIntoByteArray());
            }

            throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
        }