Mongodb 自定义反序列化

Mongodb 自定义反序列化,mongodb,mongodb-.net-driver,Mongodb,Mongodb .net Driver,我收集了数千个文档,在文档中有一个名为Rate的字段,问题是当前它的类型是string,所以当它不可用时,老开发人员将其设置为“N/A”。现在,我想将此字段的类型更改为C#中的数字(当n/a时将其设置为0),但如果这样做,则无法加载过去的数据。 我们是否可以自定义反序列化,使其将N/A转换为0?您需要创建一个IBsonSerializer或SerializerBase,并将其附加到要使用BsonSerializerAttribute进行序列化的属性。如下所示: public class Bson

我收集了数千个文档,在文档中有一个名为Rate的字段,问题是当前它的类型是string,所以当它不可用时,老开发人员将其设置为“N/A”。现在,我想将此字段的类型更改为C#中的数字(当n/a时将其设置为0),但如果这样做,则无法加载过去的数据。
我们是否可以自定义反序列化,使其将N/A转换为0?

您需要创建一个
IBsonSerializer
SerializerBase
,并将其附加到要使用
BsonSerializerAttribute
进行序列化的属性。如下所示:

public class BsonStringNumericSerializer : SerializerBase<double>
{
    public override double Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var type = context.Reader.GetCurrentBsonType();
        if (type == BsonType.String)
        {
            var s = context.Reader.ReadString();
            if (s.Equals("N/A", StringComparison.InvariantCultureIgnoreCase))
            {
                return 0.0;
            }
            else
            {
                return double.Parse(s);
            }
        }
        else if (type == BsonType.Double)
        {
            return context.Reader.ReadDouble();
        }
        // Add any other types you need to handle
        else
        {
            return 0.0;
        }
    }
}

public class YourClass
{
    [BsonSerializer(typeof(BsonStringNumericSerializer))]
    public double YourDouble { get; set; }
}
公共类BsonStringNumericSerializer:SerializerBase
{
公共重写双反序列化(BsonDeserializationContext,BsonDeserializationArgs-args-args)
{
var type=context.Reader.GetCurrentBsonType();
if(type==BsonType.String)
{
var s=context.Reader.ReadString();
if(s.Equals(“N/A”,StringComparison.InvariantCultureInogoreCase))
{
返回0.0;
}
其他的
{
返回double.Parse;
}
}
else if(type==BsonType.Double)
{
返回context.Reader.ReadDouble();
}
//添加您需要处理的任何其他类型
其他的
{
返回0.0;
}
}
}
公共课你的课
{
[BsonSerializer(typeof(BsonStringNumericSerializer))]
public double yourdoull{get;set;}
}
如果不想使用属性,可以创建一个
IBsonSerializationProvider
,并使用
BsonSerializer.RegisterSerializationProvider
注册它

可以找到MongoDB C#Bson序列化的完整文档