How to compare two Json objects using C#

后端 未结 6 1810
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 20:55

    One option is to deserialize the json strings into C# objects and compare them.

    This approach requires more work comparing to using JToken.DeepEquals (as suggested by @JessedeWit), but has the advantage of giving better error messages if your tests fail (see screenshot below).

    Your json string can be modelled into the following class:

    public class Entity
    {
        [JsonProperty("Name")]
        public string Name { get; set; }
    
        [JsonProperty("objectId")]
        public string ObjectId { get; set; }
    }
    

    In your test, deserialize the json strings into objects and compare them:

    [TestFixture]
    public class JsonTests
    {
        [Test]
        public void JsonString_ShouldBeEqualAsExpected()
        {
            string jsonExpected = @"{ ""Name"": ""20181004164456"", ""objectId"": ""4ea9b00b-d601-44af-a990-3034af18fdb1%>"" }";
            string jsonActual = @"{ ""Name"": ""AAAAAAAAAAAA"", ""objectId"": ""4ea9b00b-d601-44af-a990-3034af18fdb1%>"" }";
    
            Entity expectedObject = JsonConvert.DeserializeObject(jsonExpected);
            Entity actualObject = JsonConvert.DeserializeObject(jsonActual);
    
            actualObject.Should().BeEquivalentTo(expectedObject);
        }
    }
    

    PS: I used NUnit and FluentAssertions in my test method. Running the test:

提交回复
热议问题