How to compare two Json objects using C#

后端 未结 6 1817
我在风中等你
我在风中等你 2021-02-05 19:57

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

string InstanceExpected = jsonExpected;
string InstanceAc         


        
6条回答
  •  礼貌的吻别
    2021-02-05 20:43

    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:

提交回复
热议问题