Skip to content

Instantly share code, notes, and snippets.

@eduardocoelho
Created January 19, 2013 21:06
Show Gist options
  • Save eduardocoelho/4575133 to your computer and use it in GitHub Desktop.
Save eduardocoelho/4575133 to your computer and use it in GitHub Desktop.
C# Sort JSON string keys using System.Json (see http://stackoverflow.com/questions/14417235/c-sharp-sort-json-string-keys )
//
// JsonHelper.cs
//
// Created by Eduardo Coelho <dev@educoelho.com>
//
using System;
using System.Json;
using System.Linq;
using NUnit.Framework; // Tests
namespace JsonHelperSample
{
public class JsonHelper
{
#region Sort
public static string Sort (string jsonString)
{
if (jsonString != null) {
var jObj = (JsonObject)JsonValue.Parse (jsonString);
Sort (jObj);
return jObj.ToString ();
}
return null;
}
#endregion
#region Private
static void Sort (JsonObject jObj)
{
var props = jObj.ToList ();
foreach (var prop in props) {
jObj.Remove (prop.Key);
}
foreach (var prop in props.OrderByDescending(p => p.Key)) {
jObj.Add (prop);
if (prop.Value is JsonObject)
Sort ((JsonObject)prop.Value);
}
}
#endregion
}
[TestFixture]
public class JsonHelperSortTests
{
[Test]
public void TestSortNull ()
{
string sourceString = null;
string sortedString = JsonHelper.Sort (sourceString);
Assert.Null (sortedString);
}
[Test]
public void TestSortEmptyJSONObject ()
{
string sourceString = "{}";
string sortedString = JsonHelper.Sort (sourceString);
Assert.AreEqual (sourceString, sortedString);
}
[Test]
public void TestSortNestedJSONObjects ()
{
string sourceString = "{\"birthday\": \"1988-03-18\", \"address\": {\"state\": 24, \"city\": 8341, \"country\": 1 }}";
string sortedString = JsonHelper.Sort (sourceString);
string expectedString = "{\"address\": {\"city\": 8341, \"country\": 1, \"state\": 24}, \"birthday\": \"1988-03-18\"}";
Assert.AreEqual (expectedString, sortedString);
}
}
}
@shrivsk
Copy link

shrivsk commented May 17, 2017

	public void TestSortNestedJSONObjects ()
	{
		string sourceString = "{\"birthday\": \"1988-03-18\",""}";
			Assert.AreEqual (expectedString, sortedString);
	}

@quasibot
Copy link

Thanks a lot man!

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