Sort Properties in JSON Object using Newtonsoft.Json

Sort Properties in JSON Object using Newtonsoft.Json

This post is applicable if you are using Newtonsoft.Json for serialization/deserialization. In this article, I'm sharing C# code to sort the properties in the JSON Object.

The order of properties in a JSON object is undefined, so the properties are listed in the order they were added to the object

Sample JSON String

String jsonString = @"{""Email"":""john@mail.com"",""Website"":""http://samplewebsite.com"",""Name"":""John Smith"",""Phone"":""(50)345872""}";

Convert JSON String to JObject

JObject jsonData = JObject.Parse(jsonString);

Sort the Properties By Name

static void Main(string[] args)
{
   string jsonString = @"{""Email"":""john@mail.com"",""Website"":""http://samplewebsite.com"",""Name"":""John Smith"",""Phone"":""(50)345872""}";
   JObject jsonData = JObject.Parse(jsonString);
   Sort(jsonData);
   Console.WriteLine(jsonData.ToString());
}

private static void Sort(JObject jObj)
{
   var props = jObj.Properties().ToList();
   foreach (var prop in props)
   {
      prop.Remove();
   }

   foreach (var prop in props.OrderBy(p => p.Name))
   {
      jObj.Add(prop);
      if (prop.Value is JObject)
        Sort((JObject)prop.Value);
   }
}

Sorted JSON

{
  "Email": "john@mail.com",
  "Name": "John Smith",
  "Phone": "(50)345872",
  "Website": "http://samplewebsite.com"
}

Post a Comment

Previous Post Next Post