Why does serializing a NameValueCollection incur a loss of data?

191 Views Asked by At

For example if we have {"Parameters":["name" : "test"]} it will be serialized to {"Parameters":["name"]}. (Using System.Text.Json)

Why is that?

EDIT: See this issue that brought this to my attention, and the following code that does serialization/deserialization.

EDIT 2: Added even more clarity to those that can't follow through the above given materials

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

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

Serializes to {"Properties":["test1","test2"]}.

1

There are 1 best solutions below

0
On BEST ANSWER

It's due to the nature of NameValueCollection. It's iteration is over the key and not the key and value pair.

Thst's why one must do the following to get values when iterating:

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

All serializers just iterate all enumerables, they do not understand what is actually returned.

A much better fit is the Dictionary<string, string>.

In your case:

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

Which will return what you expected. If you want a case insensitive dictionary, just add that as an parameter when creating it: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);