Skip to content

Stable Dictionary sorting for System.Text.Json #76008

@krwq

Description

@krwq

Serializing the same dictionary but with entries added in different order in STJ can result in different results every time you run your app. We should offer converter/option which can make this behavior stable.

Repro:

using System.Text.Json;

Test repro = new Test();

if (Environment.TickCount % 2 == 0)
{
    repro.Dict.Add("left", "foo");
    repro.Dict.Add("right", "bar");
}
else
{
    repro.Dict.Add("right", "bar");
    repro.Dict.Add("left", "foo");
}

Console.WriteLine(JsonSerializer.Serialize(repro));

public class Test
{
    public Dictionary<string, string> Dict { get; } = new();
}

Output (randomly one of the following two):

{"Dict":{"left":"foo","right":"bar"}}

or

{"Dict":{"right":"bar","left":"foo"}}

Expected output:

{"Dict":{"left":"foo","right":"bar"}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions