定制反序列化 [英] Custom deserialization

查看:146
本文介绍了定制反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have collection with thousands of documents, in document there's field named Rate, problem is currently its type is string, so when it's not available, the old developer set it to "N/A". For now I want to change the type of this field to numeric in C# (set it to 0 when n/a), but if I do so I can't load the past data. Can we customize the deserialization so it will convert N/A to 0?

推荐答案

您需要创建IBsonSerializerSerializerBase<>并将其附加到要使用BsonSerializerAttribute进行序列化的属性.类似于以下内容:

You need to create an IBsonSerializer or SerializerBase<> and attach it to the property you wish to serialize using the BsonSerializerAttribute. Something like the following:

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注册它.

If you don't want to use attributes you can create an IBsonSerializationProvider and register it using BsonSerializer.RegisterSerializationProvider.

可以找到这里

这篇关于定制反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆