且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#比较两个Json对象

更新时间:2022-11-17 14:41:45

我做了更多的挖掘工作,并且能够找出为什么OP的测试代码未按预期运行的原因.我能够通过安装并使用 FluentAssertions.Json nuget包来修复它.

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.

一件重要的事情:

请确保包含using FluentAssertions.Json,否则为false 肯定会发生.

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

测试代码如下:

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);
    }
}

运行测试: