Last active
May 3, 2024 02:52
-
-
Save rpbeukes/aede77e81d514cfb2d9d4ad375cc2070 to your computer and use it in GitHub Desktop.
Serialize Object With Properties Alphabetically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var sortedJSON = CustomJsonConvert.SerializeObjectWithPropertiesAlphabetically(someObject);