将对象反序列化为数组

问题描述 投票:0回答:1

我有一个混合类型的字段(对象或对象数组)。现在我正在尝试用这个将字段反序列化为对象数组

    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:ReadBsonType只能在以下情况下调用 状态是类型,而不是当状态是值时。在 MongoDB.Bson.IO.BsonReader.ThrowInvalidState(String methodName, BsonReaderState[] validStates) 在 MongoDB.Bson.IO.BsonBinaryReader.ReadBsonType() 在 MongoDB.Bson.Serialization.BsonClassMapSerializer

1.DeserializeClass(BsonDeserializationContext context)    at MongoDB.Bson.Serialization.BsonClassMapSerializer
1.Deserialize(BsonDeserializationContext 上下文,BsonDeserializationArgs args)位于 MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 序列化器,BsonDeserializationContext 上下文)

不知道我做错了什么。

mongodb mongodb-.net-driver
1个回答
0
投票

代码中的问题:

  1. 读取器状态管理不正确。
  2. 序列化方法使用不当。

如何解决问题:

  1. 正确管理阅读器状态。
  2. 根据BSON类型正确反序列化。

固定代码:

public override Association[] Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
    var reader = context.Reader;
    switch (reader.GetCurrentBsonType())
    {
        case BsonType.Array:
            var arraySerializer = new ArraySerializer<Association>();
            return arraySerializer.Deserialize(context, args);
        case BsonType.Document:
            Association association;
            reader.ReadStartDocument();
            var bsonDocument = new BsonDocumentSerializer().Deserialize(context, args);
            association = BsonSerializer.Deserialize<Association>(bsonDocument);
            reader.ReadEndDocument();
            return new[] { association };
        default:
            throw new NotSupportedException($"Unsupported BSON type {reader.GetCurrentBsonType()}");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.