Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpbeukes/aede77e81d514cfb2d9d4ad375cc2070 to your computer and use it in GitHub Desktop.
Save rpbeukes/aede77e81d514cfb2d9d4ad375cc2070 to your computer and use it in GitHub Desktop.
Serialize Object With Properties Alphabetically
public static class CustomJsonConvert
{
/// <summary>
///Use Newtonsoft.Json.JsonConvert.SerializeObject(object) under the hood,
///with JsonSerializerSettings with a ContractResolver which takes care of the sorting of the properties.
/// </summary>
public static string SerializeObjectWithPropertiesAlphabetically(this object value, Newtonsoft.Json.Formatting formatting = Newtonsoft.Json.Formatting.Indented)
{
var jsonSerializerSettings = new JsonSerializerSettings()
{
Formatting = formatting,
ContractResolver = new OrderedPropertiesAlphabeticallyAscContractResolver()
};
return JsonConvert.SerializeObject(value, jsonSerializerSettings);
}
}
class OrderedPropertiesAlphabeticallyAscContractResolver : DefaultContractResolver
{
public OrderedPropertiesAlphabeticallyAscContractResolver() { }
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return base.CreateProperties(type, memberSerialization)
.OrderBy(p => p.Order ?? int.MaxValue) // Honor any explicit ordering first
.ThenBy(p => p.PropertyName, StringComparer.Ordinal)
.ToList();
}
}
@rpbeukes
Copy link
Author

rpbeukes commented May 3, 2024

var sortedJSON = CustomJsonConvert.SerializeObjectWithPropertiesAlphabetically(someObject);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment