【问题标题】:Serialize the List<string> value within a Dictionary<string, List<string>> as simple array将 Dictionary<string, List<string>> 中的 List<string> 值序列化为简单数组
【发布时间】:2019-01-22 17:53:41
【问题描述】:

使用 Mongo .Net Driver 2.7.2,我正在尝试自定义 Dictionary 属性的序列化方式。具体来说,我希望 Dictionary 的值 List&lt;string&gt; 序列化为一个简单的数组。

序列化器生成的当前文档结构

这就是属性当前的序列化方式。如您所见,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&lt;string&gt; 序列化为一个简单的字符串数组?

偏好是流畅的映射解决方案,而不是使用属性。

【问题讨论】:

  • 你对 linq 持开放态度吗?
  • 不确定您的意思。在哪一部分使用 Linq?
  • 转换public Dictionary&lt;string, List&lt;string&gt;&gt; ---> Array
  • 我对 Linq 这样做很满意,但是我的问题是专门关于通过 MongoDb 驱动程序进行序列化/反序列化的。我想指示驱动程序如何在 mongo 数据库中表示我的属性。例如,提供了一种方法来指示驱动程序如何处理enums 的序列化,如此处所述mongodb.github.io/mongo-csharp-driver/2.5/reference/bson/…
  • 你想要一个数组中所有键的值?

标签: c# mongodb mongodb-.net-driver


【解决方案1】:

包括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();

【讨论】:

  • 这如何回答这个问题?再次:如何指示序列化程序序列化字典的值,.NET 类型 List 序列化为一个简单的字符串数组?
  • 也许你可以扩展一个使用Dictionary的方法给你array
猜你喜欢
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
相关资源
最近更新 更多