Serialization of a byte array in JSON.NET

Given this simple class:

class HasBytes { public byte[] Bytes { get; set; } } 

I can put it through JSON.NET so that the byte array is encoded in base-64:

 var bytes = new HasBytes { Bytes = new byte[] { 1, 2, 3, 4 } }; var json = JsonConvert.SerializeObject(bytes); 

Then I can read it again in this slightly complicated form:

 TextReader textReader = new StringReader(json); JsonReader jsonReader = new JsonTextReader(textReader); var result = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); 

Things are good. But if I first include the contents of jsonReader in the JToken :

 var jToken = JToken.ReadFrom(jsonReader); 

And then push this back to jsonReader , wrapping it in a JTokenReader :

 jsonReader = new JTokenReader(jToken); 

Then deserialization throws an exception: "Expected bytes, but received a string."

Shouldn't the new JsonReader be logically equivalent to the original? Why is the "raw" JsonTextReader able to process a string as an array with a base-64 byte, while the JTokenReader version JTokenReader not work?

+7
serialization bytearray
source share
1 answer

This seems to be a bug in the JTokenReader, as far as I can see, so I reported it here .

Update: fixed in JSON.NET 3.5.

+6
source share

All Articles