1

I have a method that serialises a data object in the BSON format - it works well. I have tried to extend the method so that I can use it on collections but am running into an issue when deserialising the data. My serialisation method looks like this:

public byte[] SerializeCollection(T[] items)
{
    JsonConvert.SerializeObject(items);

    using (MemoryStream ms = new MemoryStream())
    {
        using (BsonDataWriter writer = new BsonDataWriter(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(writer, items, typeof(T[]));
        }
        return ms.ToArray();
    }
}

and my deserialisation method like this:

public T[] DeserializeCollection(byte[] bytes, JsonSerializerSettings settings)
{
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        using (BsonDataReader reader = new BsonDataReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T[]>(reader);
        }
    }
}

What I am finding is that when I deserialise the object it breaks at serializer.Deserialize<T[]>(reader) with the message:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'ServiceBusSerialisationTests.Models.TestEventModel[]' 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. Path '0'.'

Digging a bit deeper this seems to because of a problem with serialisation. When the object is serialised it effectively becomes a single object rather than array. i.e.

{ 0: {}, 1: {}, 2: {}, ...}

rather than

[{}, {}, {}, ...]

What can I do to either serialise the object correctly - as an array - or deserialise it from the object back into an array?

I am using .Net Core 2.2 and Newtonsoft.Json.Bson 1.0.2.

SBFrancies
  • 3,987
  • 2
  • 14
  • 37

0 Answers0