我有一个混合类型的字段(对象或对象数组)。现在我尝试用 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();
}
}
}
但我收到此错误
System.InvalidOperationException:只有 State 为 Type 时才能调用 ReadBsonType,State 为 Value 时则不能调用。
在 MongoDB.Bson.IO.BsonReader.ThrowInvalidState(String methodName, BsonReaderState[] validStates)
在 MongoDB.Bson.IO.BsonBinaryReader.ReadBsonType()
在 MongoDB.Bson.Serialization.BsonClassMapSerializer1.Deserialize(BsonDeserializationContext 上下文,BsonDeserializationArgs args)1.DeserializeClass(BsonDeserializationContext context) at MongoDB.Bson.Serialization.BsonClassMapSerializer
在 MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 序列化器,BsonDeserializationContext 上下文)
不知道我做错了什么。
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"
}
}
问题可能出在
BsonType.Document
情况下处理 BSON 文档反序列化的方式。不要直接尝试从 Association
反序列化 BsonDocument
对象,而是尝试在 BsonSerializer.Deserialize
语句中使用 using
方法,如下所示:
case BsonType.Document:
using (var bsonReader = new BsonDocumentReader(context.Reader.ToBsonDocument()))
{
var association = BsonSerializer.Deserialize<Association>(bsonReader);
return new[] { association };
}
这可确保
BsonReader
在使用后得到正确处置,并可能解决您遇到的错误。