MongoDB - override standard Serializer for C # primitive type

I would like to change the C # Doubles view to a rounded Int64 with a four-digit shift in the serialized C # driver stack for MongoDB. In other words, store (Double) 29.99 as (Int64) 299900

I would like it to be transparent to my application. I looked at custom serializers, but I don’t want to override everything, and then turn on Type with a fallback default, as this is a bit dirty.

I see that RegisterSerializer () will not allow me to add one for an existing type and that BsonDefaultSerializationProvider has a static list of primitive serializers and is marked as internal with private members, so I cannot easily subclass.

I also see that it is possible to represent As Int64 for doubles, but this is a great conversion. I need mainly conversion and conversion in both directions of serialization.

I wish I could just give my default serializer my own serializer to override it, but that would mean a dirty hack.

Am I missing a very easy way?

+7
source share
3 answers

, . , . , , ( , ). , , ( ) , , .

RegisterSerializer , , . , , .

, - , , , , !

, :

public class CustomDoubleSerializer : BsonBaseSerializer
{
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        var rep = bsonReader.ReadInt64();
        return rep / 100.0;
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        var rep = (long)((double)value * 100);
        bsonWriter.WriteInt64(rep);
    }
}

:

BsonSerializer.RegisterSerializer(typeof(double), new CustomDoubleSerializer());

, :

public class C
{
    public int Id;
    public double X;
}

:

BsonSerializer.RegisterSerializer(typeof(double), new CustomDoubleSerializer());

var c = new C { Id = 1, X = 29.99 };
var json = c.ToJson();
Console.WriteLine(json);

var r = BsonSerializer.Deserialize<C>(json);
Console.WriteLine(r.X);
+20

, Mongo, , , . , :

public class CustomSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        if (type == typeof(decimal)) return new DecimalSerializer(BsonType.Decimal128);

        return null; // falls back to Mongo defaults
    }
}

null , Mongo.

, :

BsonSerializer.RegisterSerializationProvider(new CustomSerializationProvider());
+2

, - . , ; , , (https://jira.mongodb.org/).

- , DoubleSerializer, , Reflection, MongoDB.Bson.Serialization.Serializers.DoubleSerializer.__instance MongoDB.Bson.Serialization.BsonDefaultSerializationProvider.__serializers.

0

All Articles