6

I've two json files. They should be the same regardless formatting and ordering of elements.

For example these two jsons are equivalent because attributes and arrays are the same, only their order and the formatting type are different:

{
  "type" : "integer",
  "values": [
    {
      "value": 1
    },
    {
      "value": 2
    }
  ]
}

and

{
  "values": [
    { "value": 1 }, { "value": 2 }
  ],
  "type" : "integer"
}

If I store them into two separate strings and I compare them, obviously the comparison will say that they are different. Instead I want to check if they are equals from a semantic point of view, and they are because they have the same attributes, and respective arrays are the same.

Is there a way in C# to check that these two json are equivalent, if I store them in two separate strings?

Jepessen
  • 11,744
  • 14
  • 82
  • 149
  • 1
    Deserialize both and compare the results – Emond Apr 16 '17 at 21:41
  • Is there a way to do it without knowing in advance the format of the JSON files? Because their schema is not pre-defined, and I should be able to do it regardless the type of data contained to jsons. – Jepessen Apr 16 '17 at 21:44
  • 1
    Check this SO answer: http://stackoverflow.com/a/31926367/172769 – Luc Morin Apr 16 '17 at 21:50
  • 1
    I think you may struggle to be 100% accurate here if you don't know the structure of the JSON beforehand. For example, is `"value": 1` the same as `"value": 1.0`? – DavidG Apr 16 '17 at 22:15
  • 1
    One of the way is to Convert each json to xml and use MS XmlDiff library, here is the complete answer http://stackoverflow.com/a/21581440/920557 – Eugene Komisarenko Apr 16 '17 at 22:15

2 Answers2

10

Using Newtonsoft.Json nuget package's DeepEquals :

using Newtonsoft.Json.Linq;

var jsonText1 = File.ReadAllText(fileName1);
var jsonText2 = File.ReadAllText(fileName2);

var json1 = JObject.Parse(jsonText1);
var json2 = JObject.Parse(jsonText2);

var areEqual = JToken.DeepEquals(json1, json2);
Emond
  • 50,210
  • 11
  • 84
  • 115
  • Don't you know, can it make sorting while comparing JArrays ? – tsul Dec 25 '17 at 10:24
  • @tsul - that is a different question. Just post it as a proper question and not as a comment. – Emond Dec 25 '17 at 12:27
  • 1
    Note that `DeepEquals` may return false negatives when compared objects are created differently. For example `JToken` containing value of type `Guid` is considered different from another `JToken` with the same value but loaded as `String`. Safe to use when parsing both compare sides from string though. – Imre Pühvel Jun 15 '19 at 11:56
1

The best bet to do this is by using the "Newtonsoft.json"

Refer the below post :

Find differences between two json objects

Community
  • 1
  • 1