Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check two JSON objects are equal?

Tags:

json

c#

I'm trying to discover if two JSON strings are equal.

This is what I previously tried

var obj1 = Json.Decode("{\"ValueA\":1,\"ValueB\":2}")
var obj2 = Json.Decode("{\"ValueB\":2,\"ValueA\":1}")

// But then there seems to be no way to compare the two objects?

Surely there must exist an elegant simple way to what I thought would be a common task?

like image 648
Ally Avatar asked Feb 04 '14 14:02

Ally


2 Answers

You could use the Compare .NET Objects lib to check if the two object instances are equal. It knows how to compare lists, dictionaries, etc. and deep compares the whole object graph. It also supports detailed reporting of what is different and has many more features you might want to use in the future.

like image 38
Dejan Avatar answered Sep 20 '22 06:09

Dejan


Another way to compare json - Comparing JSON with JToken.DeepEquals

JObject o1 = new JObject
 {
    { "Integer", 12345 },
    { "String", "A string" },
    { "Items", new JArray(1, 2) }
 };

JObject o2 = new JObject
 {
    { "Integer", 12345 },
    { "String", "A string" },
    { "Items", new JArray(1, 2) }
 };

Console.WriteLine(JToken.DeepEquals(o1, o2));
like image 67
RL89 Avatar answered Sep 22 '22 06:09

RL89