public void ReadBytes() { byte[] data = Encoding.UTF8.GetBytes("Hello world!"); JObject o = new JObject( new JProperty("Test1", data) ); 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); byte[] readBytes = jsonReader.ReadAsBytes(); Assert.AreEqual(data, readBytes); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var packet = new Packet(); JToken token = null; Action <string> Deserialize = (string name) => { jsonObject.TryGetValue(name, StringComparison.CurrentCulture, out token); }; Deserialize("ID"); packet.packetID = token.Value <byte>(); Deserialize("TypeID"); packet.type = (Packet.PacketType)token.Value <ulong>(); Deserialize("Length"); packet.incomingLength = token.Value <int>(); Deserialize("GUID"); packet.incomingGUID = token.Value <ulong>(); Deserialize("Data"); JTokenReader read = new JTokenReader(token); byte[] data = read.ReadAsBytes(); packet.Write(data, 0, data.Length); packet.Position = 1; return(packet); }
public void ReadAsBytes_Integer_Success() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, reader.ReadAsBytes()); }
public void ReadAsBytes_Array() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); byte[] bytes = reader.ReadAsBytes(); Assert.AreEqual(2, bytes.Length); Assert.AreEqual(1, bytes[0]); Assert.AreEqual(2, bytes[1]); }
public void ReadBytesFailure() { 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(); } }
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'."); }