Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array serialization in JSON.NET

Given this simple class:

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

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

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

Then I can read it back again in this slightly over-complicated way:

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

All good. But if I first turn the contents of jsonReader into a JToken:

var jToken = JToken.ReadFrom(jsonReader);

And then turn that back into a JsonReader by wrapping it in a JTokenReader:

jsonReader = new JTokenReader(jToken);

Then the deserialization throws an exception: "Expected bytes but got string".

Shouldn't the new JsonReader be logically equivalent to the original one? Why does the "raw" JsonTextReader have the ability to treat a string as a base-64 byte array whereas the JTokenReader version does not?

like image 834
Daniel Earwicker Avatar asked Apr 15 '10 11:04

Daniel Earwicker


1 Answers

This appears to be a bug in JTokenReader as far as I can see, so I've reported it here.

Update: fixed in JSON.NET 3.5 release 7.

like image 54
Daniel Earwicker Avatar answered Sep 28 '22 07:09

Daniel Earwicker