Created
May 6, 2024 00:33
-
-
Save rpbeukes/3bfa426f89ff8295da43d6c425576b72 to your computer and use it in GitHub Desktop.
NewtonsoftJsonFormatter.OrderedPropertiesAlphabeticallyAsc
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 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; | |
} | |
} | |
} |
Author
rpbeukes
commented
May 6, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment