如何使用 C# 比较两个 Json 对象 [英] How to compare two Json objects using C#

查看:74
本文介绍了如何使用 C# 比较两个 Json 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Json 对象,如下需要比较.我正在使用 Newtonsoft 库进行 Json 解析.

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

我正在使用 Fluent Assertions 来比较它.但问题是 Fluent 断言仅在属性计数/名称不匹配时才会失败.如果 json 值不同,则通过.当价值观不同时,我需要失败.

InstanceObjActual.Should().BeEquivalentTo(InstanceObjExpected);

例如,我将实际和预期的 json 进行比较,如下所示.并用上面的比较方式使它们通过,这是错误的.

<代码>{"姓名": "20181004164456","objectId": "4ea9b00b-d601-44af-a990-3034af18fdb1%>"}{"名称": "AAAAAAAAAAAA","objectId": "4ea9b00b-d601-44af-a990-3034af18fdb1%>"}

解决方案

我进行了更多的挖掘,并找出了 OP 的测试代码没有按预期运行的原因.我能够通过安装和使用

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%>"  
}

解决方案

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:

这篇关于如何使用 C# 比较两个 Json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆