将字典<long,VALUE>序列化为BSON文档

Mr.*_*oor 2 mongodb-.net-driver

我想Dictionary<long, VALUE>在MongoDB中序列化以下JSON.

{
   "213" : {},
   "63624" : {},
   ...
}
Run Code Online (Sandbox Code Playgroud)

我不想要其他的DictionaryRepresentation除外DictionaryRepresentation.Document.Document

我正在使用MongoDB C#驱动程序(v2.0.1.27),将long类型密钥转换为智能并不聪明string,这会导致异常.

谢谢

Rob*_*tam 5

您可以使用现有的序列化程序执行此操作,但它需要少量配置.

假设以下课程:

public class C
{
    public int Id { get; set; }
    public Dictionary<long, long> D { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您可以为D属性(Dictionary)配置自定义序列化程序,该属性使用将longs序列化为字符串的键序列化程序.代码如下所示:

BsonClassMap.RegisterClassMap<C>(cm =>
{
    cm.AutoMap();
    var customDictionarySerializer = new DictionaryInterfaceImplementerSerializer<Dictionary<long, long>>(
        dictionaryRepresentation: DictionaryRepresentation.Document,
        keySerializer: new Int64Serializer(BsonType.String),
        valueSerializer: BsonSerializer.SerializerRegistry.GetSerializer<long>());
    cm.GetMemberMap(c => c.D).SetSerializer(customDictionarySerializer);
});
Run Code Online (Sandbox Code Playgroud)

这里的关键思想是,即使键和值都是长的,我们也会为键和值使用不同的序列化器.

如果我们然后运行快速测试:

var document = new C { Id = 1, D = new Dictionary<long, long> { { 2, 3 } } };
var json = document.ToJson();
Console.WriteLine(json);
Run Code Online (Sandbox Code Playgroud)

我们看到Dictionary键现在被序列化为字符串:

{ "_id" : 1, "D" : { "2" : NumberLong(3) } }
Run Code Online (Sandbox Code Playgroud)