为什么序列化 NameValueCollection 会导致数据丢失?

Why does serializing a NameValueCollection incur a loss of data?

例如,如果我们有 {"Parameters":["name" : "test"]},它将被序列化为 {"Parameters":["name"]}。 (使用 System.Text.Json

这是为什么?

编辑: 参见 this issue that brought this to my attention, and the following code serialization/deserialization。

编辑 2: 为那些无法遵循上述给定材料的人增加了更多的清晰度

var asd = new SomeObject()
{
    Properties = new NameValueCollection
    {
        { "test1", "ok1" },
        { "test2", "ok2" }
    }
};

Console.WriteLine(System.Text.Json.JsonSerializer.Serialize<SomeObject>(asd));

序列化为 {"Properties":["test1","test2"]}

这是由于 NameValueCollection 的性质造成的。它的迭代遍历 key 而不是键值对。

这就是为什么在迭代时必须执行以下操作来获取值的原因:

foreach (var key in yourCollection)
{
    Console.WriteLine($"Key {key} value {yourCollection[key]}.");
}

所有的序列化程序只是迭代所有的枚举,他们不理解实际上是什么 returned。

更合适的是 Dictionary<string, string>

你的情况:

var asd = new SomeObject()
{
    Properties = new Dictionary<string, string>
    {
        { "test1", "ok1" },
        { "test2", "ok2" }
    }
};

这将 return 您所期望的。如果你想要一个不区分大小写的字典,只需在创建它时将其添加为参数:new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);