序列化Dictionary< long,VALUE>到BSON文档 [英] Serialize Dictionary<long, VALUE> to BSON documents

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

问题描述

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

I want to serialize Dictionary<long, VALUE> to following JSON in MongoDB.

{
   "213" : {},
   "63624" : {},
   ...
}

除了DictionaryRepresentation.Document.Document

我正在使用MongoDB C#驱动程序(v2.0.1.27),并且将long类型的键转换为string并导致异常是不明智的.

I am using MongoDB C# Driver (v2.0.1.27), and it is not smart to convert the long type key into string, which causes an exception.

推荐答案

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

You can do this with the existing serializers but it requires a small amount of configuration.

假设以下课程:

public class C
{
    public int Id { get; set; }
    public Dictionary<long, long> D { get; set; }
}

您可以为D属性(字典)配置一个自定义序列化程序,该序列化程序使用一个将序列号序列化为字符串的键序列化器.代码如下:

You can configure a custom serializer for the D property (the Dictionary) that uses a key serializer that serializes longs to strings. The code would look like this:

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);
});

这里的关键思想是,即使键和值都是long型的,我们对于键和值也使用了不同的序列化器.

The key idea here is that even though the keys and values are both longs, we are using different serializers for the keys and the values.

如果我们随后进行快速测试:

If we then run a quick test:

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

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

We see that the Dictionary keys are now being serialized as strings:

{ "_id" : 1, "D" : { "2" : NumberLong(3) } }

这篇关于序列化Dictionary&lt; long,VALUE&gt;到BSON文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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