When serializing object of KeyValuePair the serializer doesn't take JsonNamingPolicy.CamelCase option into consideration. The following example code tries to depict the situation.
class Program
{
static void Main(string[] args)
{
var opt = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var kvp = new KeyValuePair<string, string>("one", "1");
Console.WriteLine("Without Option: " + JsonSerializer.Serialize(kvp));
Console.WriteLine("With Option: " + JsonSerializer.Serialize(kvp, opt));
}
}
Result:
Without Option: {"Key":"one","Value":"1"}
With Option: {"Key":"one","Value":"1"}
Expected Result:
Without Option: {"Key":"one","Value":"1"}
With Option: {"key":"one","value":"1"}
.NET Version: Core 3.1
OS: Windows 10 20H2
Architecture: x64
With .NET 5, it gives the expected output:
Without Option: {"Key":"one","Value":"1"}
With Option: {"key":"one","value":"1"}
For netcoreapp 3.x, we can reference the latest NuGet package in project file: https://www.nuget.org/packages/System.Text.Json.
This was fixed in .NET 5 (https://github.com/dotnet/runtime/pull/36424). See breaking change notes about the new behavior https://docs.microsoft.com/dotnet/core/compatibility/3.1-5.0#propertynamingpolicy-propertynamecaseinsensitive-and-encoder-options-are-honored-when-serializing-and-deserializing-key-value-pairs.
Most helpful comment
With .NET 5, it gives the expected output:
For netcoreapp 3.x, we can reference the latest NuGet package in project file: https://www.nuget.org/packages/System.Text.Json.