user2161442
user2161442

Reputation: 21

Serialize JSON in alphabetical order

Here's the situation, I first generate 2 JSON from objects of each class of my model. One JSON is from my current model version and the other is from a previous version of it. My job is to compare each JSON to find where are the difference between the 2 models.

The problems is, the attributes of the objects are not serialized in the same order from one JSON to another.

Is there a way two serialize an object with all their attribute in alphabetical order, so I can compare both of the string easily ?

Thanks !

Upvotes: 2

Views: 3372

Answers (1)

cgotberg
cgotberg

Reputation: 2085

If you just want to do a one time compare on 2 json strings there's this resource on the web

http://tlrobinson.net/projects/javascript-fun/jsondiff

In Json.Net there is a DeepEquals available on JToken so.

var json1 = JToken.Parse(jsonString1);
var json2 = JToken.Parse(jsonString2);
var jsonEqual = JToken.DeepEquals(json1, json2);

If you want to do exactly what you're asking Order the serialization see this post.

https://stackoverflow.com/a/11309106/1181408

Update - Show that Order serialization works fine.

public class OrderedContractResolver : DefaultContractResolver
{
    protected override System.Collections.Generic.IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
    }
}

public class JsonSerializationTest1
{
    public string Test1 { get; set; }
    public string MyTest2 { get; set; }
    public string Test2 { get; set; }
    public string Test10 { get; set; }
}

public class JsonSerializationTest2
{
    public string Test10 { get; set; }
    public string Test1 { get; set; }
    public string MyTest2 { get; set; }
    public string Test2 { get; set; }
}

[TestMethod]
    public void TestJsonOrder()
    {
        var test1 = new JsonSerializationTest1 { Test1 = "abc", MyTest2 = "efg", Test10 = "hij", Test2 = "zyx" };
        var test2 = new JsonSerializationTest2 { Test1 = "abc", Test10 = "hij", Test2 = "zyx", MyTest2 = "efg" };

        var test1Json = JsonConvert.SerializeObject(test1);
        var test2Json = JsonConvert.SerializeObject(test2);

        Assert.AreNotEqual(test1Json, test2Json);

        var settings = new JsonSerializerSettings()
        {
            ContractResolver = new OrderedContractResolver()
        };

        var json1 = JsonConvert.SerializeObject(test1, Formatting.Indented, settings);
        var json2 = JsonConvert.SerializeObject(test2, Formatting.Indented, settings);

        Assert.AreEqual(json1, json2);

    }

Upvotes: 4

Related Questions