gpt4 book ai didi

c# - 将 Dictionary 序列化为 BSON 时出现 BsonSerializationException

转载 作者:IT老高 更新时间:2023-10-28 13:06:13 32 4
gpt4 key购买 nike

我最近搬到了 new MongoDB C# driver v2.0来自 deprecated v1.9 .

现在,当我序列化具有字典的类时,有时会遇到以下 BsonSerializationException:

MongoDB.Bson.BsonSerializationException: When using DictionaryRepresentation.Document key values must serialize as strings.

这是一个最小的复制:

class Hamster
{
public ObjectId Id { get; private set; }
public Dictionary<DateTime,int> Dictionary { get; private set; }
public Hamster()
{
Id = ObjectId.GenerateNewId();
Dictionary = new Dictionary<DateTime, int>();
Dictionary[DateTime.UtcNow] = 0;
}
}

static void Main()
{
Console.WriteLine(new Hamster().ToJson());
}

最佳答案

问题是新驱动默认将字典序列化为文档。

MongoDB C# 驱动程序有 3 种方法来序列化字典:DocumentArrayOfArraysArrayOfDocuments (more on that in the docs)。当它序列化为文档时,字典键是 BSON 元素的名称,它有一些限制(例如,如错误所示,它们必须序列化为字符串)。

在这种情况下,字典的键是 DateTimes 不是序列化为字符串,而是 Dates 所以我们需要选择另一个 DictionaryRepresentation

要更改此特定属性的序列化,我们可以使用具有不同 DictionaryRepresentationBsonDictionaryOptions 属性:

[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
public Dictionary<DateTime, int> Dictionary { get; private set; }

但是,我们需要对每个有问题的成员单独执行此操作。要将此 DictionaryRepresentation 应用于所有相关成员,我们可以实现一个新约定:

class DictionaryRepresentationConvention : ConventionBase, IMemberMapConvention
{
private readonly DictionaryRepresentation _dictionaryRepresentation;
public DictionaryRepresentationConvention(DictionaryRepresentation dictionaryRepresentation)
{
_dictionaryRepresentation = dictionaryRepresentation;
}
public void Apply(BsonMemberMap memberMap)
{
memberMap.SetSerializer(ConfigureSerializer(memberMap.GetSerializer()));
}
private IBsonSerializer ConfigureSerializer(IBsonSerializer serializer)
{
var dictionaryRepresentationConfigurable = serializer as IDictionaryRepresentationConfigurable;
if (dictionaryRepresentationConfigurable != null)
{
serializer = dictionaryRepresentationConfigurable.WithDictionaryRepresentation(_dictionaryRepresentation);
}

var childSerializerConfigurable = serializer as IChildSerializerConfigurable;
return childSerializerConfigurable == null
? serializer
: childSerializerConfigurable.WithChildSerializer(ConfigureSerializer(childSerializerConfigurable.ChildSerializer));
}
}

我们注册如下:

ConventionRegistry.Register(
"DictionaryRepresentationConvention",
new ConventionPack {new DictionaryRepresentationConvention(DictionaryRepresentation.ArrayOfArrays)},
_ => true);

关于c# - 将 Dictionary<DateTime,T> 序列化为 BSON 时出现 BsonSerializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111846/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com