How to compare two Json objects using C#
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:
How compare two json objects by only key?
One way you could achive this is by retrieving the names/path of all keys in json and comparing the List. For example,
var path1 = GetAllPaths(json1).OrderBy(x=>x).ToList();
var path2 = GetAllPaths(json2).OrderBy(x=>x).ToList();
var result = path1.SequenceEqual(path2);
Where GetAllPaths is defined as
private IEnumerable<string> GetAllPaths(string json)
{
var regex = new Regex(@"\[\d*\].",RegexOptions.Compiled);
return JObject.Parse(json).DescendantsAndSelf()
.OfType<JProperty>()
.Where(jp => jp.Value is JValue)
.Select(jp => regex.Replace(jp.Path,".")).Distinct();
}
Sample Demo
Check if two json are equivalent
Using Newtonsoft.Json nuget package's DeepEquals :
using Newtonsoft.Json.Linq;
var jsonText1 = File.ReadAllText(fileName1);
var jsonText2 = File.ReadAllText(fileName2);
var json1 = JObject.Parse(jsonText1);
var json2 = JObject.Parse(jsonText2);
var areEqual = JToken.DeepEquals(json1, json2);
Related Topics
C# List Join List and Filter from Another List
How to Programmatically Set the System Volume
How to Cast Object to List<Object> and Turn It into an Array
Entity Framework Core With Multiple Foreign Key on Same Column
Check If Task Is Already Running Before Starting New
How to Create ASP.NET Identity Tables in an Already Created Database Using Code First
Automapper - Map Using the Same Source and Destination Object Types
Post Json Array to MVC Controller
How to Save Mailmessage Object to Disk as *.Eml or *.Msg File
How to Create a 2D Array from a CSV File
How to Use Decimal Type in Mongodb
How to Download File With ASP.NET on Buttton'S Onclick Event
How to Check If a Windows Form Is Already Open, and Close It If It Is
How to Reference Assemblies Using Visual Studio Code
Post Byte Array to Web API Server Using Httpclient
How to Count Rows Within Entityframework Without Loading Contents