我想将Dictionary<long, VALUE>
序列化为跟随MongoDB中的JSON。
{
"213" : {},
"63624" : {},
...
}
除了DictionaryRepresentation
DictionaryRepresentation.Document.Document
我使用的是MongoDB C#驱动程序(v2.0.1.27),将long
类型密钥转换为string
是不明智的,这会导致异常。
谢谢
答案 0 :(得分:5)
您可以使用现有的序列化程序执行此操作,但需要进行少量配置。
假设以下课程:
public class C
{
public int Id { get; set; }
public Dictionary<long, long> D { get; set; }
}
您可以为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);
});
这里的关键思想是即使键和值都是长的,我们也会为键和值使用不同的序列化器。
如果我们再进行快速测试:
var document = new C { Id = 1, D = new Dictionary<long, long> { { 2, 3 } } };
var json = document.ToJson();
Console.WriteLine(json);
我们看到Dictionary键现在被序列化为字符串:
{ "_id" : 1, "D" : { "2" : NumberLong(3) } }
答案 1 :(得分:1)
我还制定了另一种解决方案,希望它可以帮助其他人
public class LongDictionarySerializer<K> : DictionarySerializerBase<Dictionary<long, K>>
{
public LongDictionarySerializer() : base(DictionaryRepresentation.Document)
{
}
protected override Dictionary<long, K> CreateInstance()
{
return new Dictionary<long, K>();
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Dictionary<long, K> value)
{
if (value != null)
{
Dictionary<string, K> dic = value.ToDictionary(d => d.Key.ToString(), d => d.Value);
BsonSerializer.Serialize<Dictionary<string, K>>(context.Writer, dic);
}
else
BsonSerializer.Serialize<object>(context.Writer, null);
}
public override Dictionary<long, K> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
Dictionary<string, K> dic = BsonSerializer.Deserialize<Dictionary<string, K>>(context.Reader);
if (dic == null)
return null;
Dictionary<long, K> ret = new Dictionary<long, K>();
foreach( var pair in dic )
{
long key;
if (!long.TryParse(pair.Key, out key))
continue;
ret[key] = pair.Value;
}
return ret;
}
}
然后在现场
[BsonElement(Fields.Markets)]
[BsonSerializer(typeof(LongDictionarySerializer<XXX>))]
public Dictionary<long, XXX> Markets { get; set; }