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"]}
.
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:
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:
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);