Newtonsoft.Json.Linq.JTokenReader.ReadAsBytes C# (CSharp) Method

ReadAsBytes() public method

Reads the next JSON token from the stream as a T:Byte[].
public ReadAsBytes ( ) : byte[]
return byte[]
    public override byte[] ReadAsBytes()
    {
      Read();

      // attempt to convert possible base 64 string to bytes
      if (TokenType == JsonToken.String)
      {
        string s = (string) Value;
        byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s);
        SetToken(JsonToken.Bytes, data);
      }

      if (TokenType == JsonToken.Bytes)
        return (byte[])Value;
      if (TokenType == JsonToken.Null)
        return null;

      throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
    }

Usage Example

        public void ReadBytesFailure()
        {
            ExceptionAssert.Throws<JsonReaderException>(() =>
            {
                JObject o =
                    new JObject(
                        new JProperty("Test1", 1)
                        );

                using (JTokenReader jsonReader = new JTokenReader(o))
                {
                    jsonReader.Read();
                    Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);

                    jsonReader.Read();
                    Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
                    Assert.AreEqual("Test1", jsonReader.Value);

                    jsonReader.ReadAsBytes();
                }
            }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'.");
        }
All Usage Examples Of Newtonsoft.Json.Linq.JTokenReader::ReadAsBytes