Runtime: `KeyValuePair` serialization doesn't follow camel case option in `System.Text.Json`

Created on 8 Nov 2020  路  2Comments  路  Source: dotnet/runtime

Description

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"}    

Configuration

.NET Version: Core 3.1
OS: Windows 10 20H2
Architecture: x64

area-System.Text.Json

Most helpful comment

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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nalywa picture nalywa  路  3Comments

sahithreddyk picture sahithreddyk  路  3Comments

jzabroski picture jzabroski  路  3Comments

bencz picture bencz  路  3Comments

aggieben picture aggieben  路  3Comments