Reputation: 130
I have two json objects and I compare them, But it is compared by key and value, And I want to compare two json objects by only key, How do I it?
This my code:
var jdp = new JsonDiffPatch();
var areEqual2 = jdp.Diff(json1, json2);
Upvotes: 0
Views: 2732
Reputation: 11
If you want to get a different between 2 json:
private List<string> GetDiff(List<string> path1, List<string> path2)
{
List<string> equal=new List<string>();
foreach (var j1 in path1)
{
foreach (var j2 in path2)
{
if (j1 == j2)
{
equal.Add(j1);
}
}
}
return equal;
}
Upvotes: 1
Reputation: 145
you can create and use a class like this:
class CustomComparer : IEqualityComparer<YourObjectType>
{
public bool Equals(YourObjectType first, YourObjectType second)
{
if (first == null | second == null) { return false; }
else if (first.Hash == second.Hash)
return true;
else return false;
}
public int GetHashCode(YourObjectType obj)
{
throw new NotImplementedException();
}
}
Upvotes: 1
Reputation: 18173
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();
}
Upvotes: 0