mongodbmongodb-.net-driver

Deserializing object to array


I have a field with mixed type (object or array of object). Now I am trying to deserialize this field into array of object with this

class AssociationSerializer : SerializerBase<Association[]>
{
    public override Association[] Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var type = context.Reader.GetCurrentBsonType();

        switch (type)
        {
            case BsonType.Array:
                var arraySerializer = new ArraySerializer<Association>();
                return arraySerializer.Deserialize(context, new BsonDeserializationArgs());

            case BsonType.Document:
                var bsonDocument = context.Reader.ToBsonDocument();
                var association= BsonSerializer.Deserialize<Association>(bsonDocument);
                return new[] { association };

            default:
                throw new NotSupportedException();
        }
    }
}

But I am getting this error

System.InvalidOperationException: ReadBsonType can only be called when State is Type, not when State is Value.
at MongoDB.Bson.IO.BsonReader.ThrowInvalidState(String methodName, BsonReaderState[] validStates)
at MongoDB.Bson.IO.BsonBinaryReader.ReadBsonType()
at MongoDB.Bson.Serialization.BsonClassMapSerializer1.DeserializeClass(BsonDeserializationContext context) at MongoDB.Bson.Serialization.BsonClassMapSerializer1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)

Not sure what I am doing wrong.

public class Association
{
    public string Id { get; set; }
    public int Type { get; set; }
}

JSON:

{   
    "association" : [
        {
            "_id" : "b8e0a770-951b-5e85-84a6-8ca8cd0998e0",
            "type" : 0
        }
    ]
}   
    
{
    "association" : {
        "_id" : "08dc1cb0-0f88-4dcf-70db-ff3b8c000003"
    }
}

Solution

  • A simplest approach I see:

     public class AssociationSerializer : SerializerBase<Association[]>
     {
         public override Association[] Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
         {
             var type = context.Reader.GetCurrentBsonType();
    
             switch (type)
             {
                 case BsonType.Array:
                     var arraySerializer = new ArraySerializer<Association>();
                     return arraySerializer.Deserialize(context, new BsonDeserializationArgs());
    
                 case BsonType.Document:
                     var value = BsonSerializer.Deserialize<Association>(context.Reader);
                     return new[] { value };
    
                 default:
                     throw new NotSupportedException();
             }
         }
     }