Skip to content

Instantly share code, notes, and snippets.

@rpbeukes
Created May 6, 2024 00:33
Show Gist options
  • Save rpbeukes/3bfa426f89ff8295da43d6c425576b72 to your computer and use it in GitHub Desktop.
Save rpbeukes/3bfa426f89ff8295da43d6c425576b72 to your computer and use it in GitHub Desktop.
NewtonsoftJsonFormatter.OrderedPropertiesAlphabeticallyAsc
public static class NewtonsoftJsonFormatter
{
public static object OrderedPropertiesAlphabeticallyAsc(dynamic dynamicJsonObj)
{
if (dynamicJsonObj is JObject jObj)
{
var sortedProperties = jObj.AsJEnumerable().OrderBy(x => x.Path).ToList();
var sortedObj = new JObject();
foreach (var item in sortedProperties)
{
if (item.OfType<JArray>().Count() > 0)
{
var list = OrderedPropertiesAlphabeticallyAsc(JArray.FromObject(item.OfType<JArray>()));
var key = item.Path.Split(".")[1];
var jprop = new JProperty(key, ((object[])list)[0]);
sortedObj.Add(jprop);
}
else
{
sortedObj.Add(item);
}
}
return sortedObj;
}
else if (dynamicJsonObj is JArray jarray)
{
var sorted = jarray.Select(x => OrderedPropertiesAlphabeticallyAsc(x)).ToArray();
return sorted;
}
else
{
return dynamicJsonObj;
}
}
}
@rpbeukes
Copy link
Author

rpbeukes commented May 6, 2024

// read un-sorted JSON
var json = await File.ReadAllTextAsync(@"SomeJSON.json");

// convert to object
var dynamicObj = JsonConvert.DeserializeObject<dynamic>(json);

// create new Object but properties are sorted alphabetically
var sortedDynamicObj = NewtonsoftJsonFormatter.OrderedPropertiesAlphabeticallyAsc(value);

// convert to JSON string
var sortedJSONStr = JsonConvert.SerializeObject(sortedDynamicObj, Formatting.Indented);

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