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.BsonClassMapSerializer
1.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"
}
}
2
Answers
It seems like the issue might be with the way you are handling the deserialization of the BSON document in the
BsonType.Document
case. Instead of directly trying to deserialize theAssociation
object from theBsonDocument
, try using theBsonSerializer.Deserialize
method within ausing
statement, like this:This ensures that the
BsonReader
is properly disposed of after use and might resolve the error you are encountering.A simplest approach I see: