Serialize to JSON in Alphabetical Order in C#

By FoxLearn 2/5/2025 7:24:07 AM   88
There are two ways to serialize an object’s properties to JSON in alphabetical order using System.Text.Json:

Manually alphabetize with JsonPropertyOrder

You can specify the exact order of properties during serialization by using the JsonPropertyOrder attribute. To serialize in alphabetical order, arrange the properties in alphabetical order and apply the JsonPropertyOrder attribute accordingly.

using System.Text.Json.Serialization;

public class Book
{
    [JsonPropertyOrder(1)]
    public string Author { get; set; }

    [JsonPropertyOrder(2)]
    public DateTime PublicationDate { get; set; }

    [JsonPropertyOrder(3)]
    public string Title { get; set; }
}

Now, you can serialize the object:

using System.Text.Json;

var book = new Book()
{
    Author = "J.K. Rowling",
    PublicationDate = new DateTime(1997, 6, 26),
    Title = "Harry Potter and the Philosopher's Stone"
};

var options = new JsonSerializerOptions() { WriteIndented = true };
var json = JsonSerializer.Serialize(book, options);

Console.WriteLine(json);

This will output the following JSON with properties in alphabetical order:

{
  "Author": "J.K. Rowling",
  "PublicationDate": "1997-06-26T00:00:00",
  "Title": "Harry Potter and the Philosopher's Stone"
}

This method is straightforward and useful for smaller projects or classes where you want precise control. However, for larger projects, an automated approach might be more efficient.

Serialize alphabetically with a contract resolver

You can automatically sort properties alphabetically during serialization by implementing a custom contract resolver (added to System.Text.Json in version 7). The process involves creating a resolver that rearranges the properties before serialization.

using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;

public class AlphabeticalOrderContractResolver : DefaultJsonTypeInfoResolver
{
    public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
    {
        var jsonTypeInfo = base.GetTypeInfo(type, options);
        int order = 1;

        foreach(var property in jsonTypeInfo.Properties.OrderBy(p => p.Name))
        {
            property.Order = order++;
        }

        return jsonTypeInfo;
    }
}

To use this resolver during serialization, configure JsonSerializerOptions as follows:

using System.Text.Json;

var book = new Book()
{
    Author = "J.K. Rowling",
    PublicationDate = new DateTime(1997, 6, 26),
    Title = "Harry Potter and the Philosopher's Stone"
};

var options = new JsonSerializerOptions() { WriteIndented = true };
options.TypeInfoResolver = new AlphabeticalOrderContractResolver();

var json = JsonSerializer.Serialize(book, options);

Console.WriteLine(json);

The output will be the same as with the manual approach:

{
  "Author": "J.K. Rowling",
  "PublicationDate": "1997-06-26T00:00:00",
  "Title": "Harry Potter and the Philosopher's Stone"
}

This automatic sorting feature is available in System.Text.Json v7.

If you’re using an earlier version of .NET, you can either:

  • Install the latest System.Text.Json package, or
  • Implement a custom JSON converter that sorts the properties before serialization, or
  • Use Newtonsoft.Json to handle sorting.