Byte array serialization in JSON.NET

Posted by Daniel Earwicker on Stack Overflow See other posts from Stack Overflow or by Daniel Earwicker
Published on 2010-04-15T11:38:30Z Indexed on 2010/04/15 11:43 UTC
Read the original article Hit count: 3177

Filed under:
|
|

Given this simple class:

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

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

var bytes = new HasBytes { Bytes = new byte[] { 1, 2, 3, 4 } };

// turn it into a JSON string
var json = JsonConvert.SerializeObject(bytes);

// get back a new instance of HasBytes
var result1 = JsonConvert.DeserializeObject<HasBytes>(json);

// all is well
Debug.Assert(bytes.Bytes.SequenceEqual(result1.Bytes));

But if I deserialize this-a-wise:

var result2 = (HasBytes)new JsonSerializer().Deserialize(
            new JTokenReader(
                JToken.ReadFrom(new JsonTextReader(
                    new StringReader(json)))), 
            typeof(HasBytes));

... it throws an exception, "Expected bytes but got string".

What other options/flags/whatever would need to be added to the "complicated" version to make it properly decode the base-64 string to initialize the byte array?

Obviously I'd prefer to use the simple version but I'm trying to work with a CouchDB wrapper library called Divan, which sadly uses the complicated version, with the responsibilities for tokenizing/deserializing widely separated, and I want to make the simplest possible patch to how it currently works.

© Stack Overflow or respective owner

Related posts about json.net

Related posts about serialization