如何使用C#比较两个Json对象 [英] How to compare two Json objects using C#
问题描述
我有两个Json对象,如下所示.我正在使用Newtonsoft库进行Json解析.
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);
我正在使用Fluent Assertions进行比较.但是问题是只有当属性计数/名称不匹配时,Fluent断言才会失败.如果json值不同,则通过.当值不同时,我要求失败.
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);
例如,我将实际和预期的json进行如下比较.并使用上述比较方法使它们通过,这是错误的.
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%>"
}
推荐答案
我做了更多的挖掘工作,并且能够找出为什么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);
}
}
运行测试:
这篇关于如何使用C#比较两个Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!