/// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Boolean}"/>. /// </summary> /// <returns>A <see cref="Nullable{Boolean}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual bool?ReadAsBoolean() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return(null); case JsonToken.Integer: case JsonToken.Float: bool b; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (Value is BigInteger) { b = (BigInteger)Value != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return(b); case JsonToken.String: return(ReadBooleanString((string)Value)); case JsonToken.Boolean: return((bool)Value); } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); }
internal JsonReaderException CreateUnexpectedEndException() { return(JsonReaderException.Create(this, "Unexpected end when reading JSON.")); }
/// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference 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(); if (t == JsonToken.None) { return(null); } if (TokenType == 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); } switch (t) { 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 = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return(data); } 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)); }