自定义反序列化
Custom deserialization
我收集了数千个文档,在文档中有一个名为Rate的字段,问题是目前它的类型是字符串,所以当它不可用时,老开发人员将它设置为"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; }
}
如果您不想使用属性,您可以创建一个 IBsonSerializationProvider
并使用 BsonSerializer.RegisterSerializationProvider
.
注册它
可以找到 MongoDB C# Bson 序列化的完整文档 here
我收集了数千个文档,在文档中有一个名为Rate的字段,问题是目前它的类型是字符串,所以当它不可用时,老开发人员将它设置为"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; }
}
如果您不想使用属性,您可以创建一个 IBsonSerializationProvider
并使用 BsonSerializer.RegisterSerializationProvider
.
可以找到 MongoDB C# Bson 序列化的完整文档 here