Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Json objects using C#

I have two Json objects as below need to be compared. I am using Newtonsoft libraries for Json parsing.

string InstanceExpected = jsonExpected;
string InstanceActual = jsonActual;
var InstanceObjExpected = JObject.Parse(InstanceExpected);
var InstanceObjActual = JObject.Parse(InstanceActual);

And I am using Fluent Assertions to compare it. But the problem is Fluent assertion fails only when the attribute count/names are not matching. If the json values are different it passes. I require to fail when values are different.

InstanceObjActual.Should().BeEquivalentTo(InstanceObjExpected);

For example I have the actual and expected json to compare as below. And using the above way of comparing make them Pass which is wrong.

{
  "Name": "20181004164456",
  "objectId": "4ea9b00b-d601-44af-a990-3034af18fdb1%>"  
}

{
  "Name": "AAAAAAAAAAAA",
  "objectId": "4ea9b00b-d601-44af-a990-3034af18fdb1%>"  
}
like image 554
Nandakumar1712 Avatar asked Oct 04 '18 11:10

Nandakumar1712


2 Answers

I did a bit more digging and was able to find out why the OP's test code doesn't run as expected. I was able to fix it by installing and using the FluentAssertions.Json nuget package.

One important thing:

Be sure to include using FluentAssertions.Json otherwise false positives may occur.

Test code is the following:

using FluentAssertions;
using FluentAssertions.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;

[TestFixture]
public class JsonTests
{
    [Test]
    public void JsonObject_ShouldBeEqualAsExpected()
    {
        JToken expected = JToken.Parse(@"{ ""Name"": ""20181004164456"", ""objectId"": ""4ea9b00b-d601-44af-a990-3034af18fdb1%>"" }");
        JToken actual = JToken.Parse(@"{ ""Name"": ""AAAAAAAAAAAA"", ""objectId"": ""4ea9b00b-d601-44af-a990-3034af18fdb1%>"" }");

        actual.Should().BeEquivalentTo(expected);
    }
}

Running the test:

Unit test results

like image 118
Rui Jarimba Avatar answered Sep 22 '22 02:09

Rui Jarimba


Consider using the JToken.DeepEquals() method provided by Newtonsoft. It would look somewhat like this, regardless of which testing framework you're using:

Console.WriteLine(JToken.DeepEquals(InstanceObjActual, InstanceObjExpected));
// false
like image 30
Jesse de Wit Avatar answered Sep 24 '22 02:09

Jesse de Wit