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; }
}
If you don't want to use attributes you can create an IBsonSerializationProvider
and register it using BsonSerializer.RegisterSerializationProvider
.
Full documentation of MongoDB C# Bson serialization can be found here
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…