使用 MongoDB.Bson 序列化对象时遇到了问题,直接对实例序列化正常,转换为 object 实例化失败,示例代码如下
using MongoDB.Bson;
TestData dt = new();
var bson = dt.ToBson(); // 可以正常序列化
Console.WriteLine(bson.Length);
object obj = dt;
bson = obj.ToBson(); // 抛异常
Console.WriteLine(bson.Length);
public class TestData
{
public string FieldA;
public string FieldB;
}
异常信息
MongoDB.Bson.BsonSerializationException: Type TestData is not configured as a type that is allowed to be serialized for this instance of ObjectSerializer.
在 stackoverflow 上的一个回答中找到解决方法
var objectSerializer = new ObjectSerializer(ObjectSerializer.AllAllowedTypes);
BsonSerializer.RegisterSerializer(objectSerializer);
上面代码中的注册是全局的,注册后 ToBson
就支持所有允许的类型,完整示例代码如下
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
TestData dt = new() { FieldA = "A" };
var bson = dt.ToBson();
Console.WriteLine(bson.Length); // output: 27
Console.WriteLine(BsonSerializer.Deserialize<TestData>(bson).FieldA);
var objectSerializer = new ObjectSerializer(ObjectSerializer.AllAllowedTypes);
BsonSerializer.RegisterSerializer(objectSerializer);
object obj = dt;
bson = obj.ToBson();
Console.WriteLine(bson.Length); // output: 44
Console.WriteLine(BsonSerializer.Deserialize<TestData>(bson).FieldA);
Console.WriteLine(((TestData)BsonSerializer.Deserialize<object>(bson)).FieldA);
public class TestData
{
public string FieldA;
public string FieldB;
}