This project has moved. For the latest updates, please go here.


Can't (de)serialize array from Bson format



I am having trouble serializing and deserializing a simple array in Bson format.
var jsonSerializer = new JsonSerializer();
var array = new string [] { "A", "B" };

// Serialization
byte[] bytes;
using (var ms = new MemoryStream())
using (var bson = new BsonWriter(ms))
    jsonSerializer.Serialize(bson, array, typeof(string[]));
    bytes = ms.ToArray();

// Deserialization
using (var ms = new MemoryStream(bytes))
using (var bson = new BsonReader(ms))
    // Exception here
    array = jsonSerializer.Deserialize<string[]>(bson);
The exception that is raised is:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.String[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
There was some discussion around this as well as work-arounds here:

In my case though the workarounds are hard to implement as I need to this to work in generic code, applicable to any type.
Closed Jun 5, 2013 at 9:00 PM by JamesNK
See SO answer