使用 Mongo .Net Driver 2.7.2,我尝试自定义 Dictionary 属性的序列化方式。具体来说,我希望将字典的值
List<string>
序列化为简单数组。
序列化器生成的当前文档结构
这就是属性当前的序列化方式。正如您所看到的,
someProperty
被序列化为对象,_t和_v存储.NET
类型和值。
viewedBy: Object
someProperty: Object
_t: "System.Collections.Generic.List`1[System.String]"
_v: Array
我知道类型信息是为了反序列化而存储回 c# POCO 中的,但就我而言,我不需要此元数据,因为我的类型只是一个字符串数组。
所需的文档结构
我希望将属性值序列化为简单的字符串数组,如下所示
viewedBy: Object
someProperty: Array
这是我尝试为其定制序列化策略的类。
public class MyDocument
{
public Dictionary<string, List<string>> ViewedBy { get; set; }
}
当前映射
这是我为班级提供的地图信息。
BsonClassMap.RegisterClassMap<MyDocument>(cm =>
{
cm.AutoMap();
cm.MapMember(c => c.ViewedBy)
.SetElementName("viewedBy")
.SetSerializer(new
DictionaryInterfaceImplementerSerializer<Dictionary<string,
List<string>>>(DictionaryRepresentation.Document));
// How do I specify the dictionary value should serialize as simple array?
});
问题
如何指示序列化器序列化字典的值(
.NET
类型List<string>
)以序列化为简单的字符串数组?
优先选择流畅的映射解决方案,而不是使用属性。
包括
System.Linq
按照您想要的方式使用它。
Dictionary<string, List<string>> m = new Dictionary<string, List<string>>();
m.Add("1", new List<string> { "Sumit", "Raj" });
m.Add("2", new List<string> { "Rahul", "Raj" });
/*Array of string. Currently 4 values*/
var res = m.SelectMany(x => x.Value).ToArray();
/*Array of List<string>. Currently 2 List With 2 Values*/
var res1 = m.Select(x => x.Value).ToArray();
您可以创建 DictionaryInterfaceImplementerSerializer 的实例,并为键和值指定序列化器:
var mySerializer = new DictionaryInterfaceImplementerSerializer<Dictionary<string, List<string>>, string, List<string>>(
dictionaryRepresentation: DictionaryRepresentation.ArrayOfDocuments,
keySerializer: BsonSerializer.SerializerRegistry.GetSerializer<string>(),
valueSerializer: BsonSerializer.SerializerRegistry.GetSerializer<List<string>>());
然后在使用 .SetSerializer(mySerializer) 映射元素“myView”时只需使用“mySerializer”实例。 学分转到此相关答案