自定义反序列化

时间:2017-02-20 04:52:22

标签: mongodb mongodb-.net-driver

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

1 个答案:

答案 0 :(得分:3)

您需要创建IBsonSerializerSerializerBase<>并使用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; }
}

如果您不想使用属性,可以创建IBsonSerializationProvider并使用BsonSerializer.RegisterSerializationProvider进行注册。

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