Created
January 19, 2013 21:06
-
-
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 )
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
// | |
// 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment