Reputation: 1259
I have two JSON objects that needs to be compared. However I want to exclude certain properties. Is there an efficient way of doing so without iterating over all the keys?
I am using JSON.NET which has JToken.DeepEquals() and is brilliant but it doesnt allow me to exclude certain keys.
Thanks!
Upvotes: 6
Views: 2596
Reputation: 854
First, as C Bauer suggested, you should deserialize the JSON to some sort of object. Then you can make a class with the IEqualityComparer interface for this object.
class Compare : IEqualityComparer<YourClass>
{
public bool Equals(YourClass x, YourClass y)
{
// add your comparison logic
return x.Property == y.Property;
}
public int GetHashCode(YourClass something)
{
// return a hashcode based on your unique properties
return something.Property.GetHashCode();
}
}
Take a look at http://www.dreamincode.net/forums/topic/352582-linq-by-example-3-methods-using-iequalitycomparer/ for a few examples of usage with LINQ.
Upvotes: 1
Reputation: 5113
Well, first I'd suggest parsing the JSON into some kind of object. We're not supposed to suggest outside tools but you should be able to find something satisfactory with a simple google search.
Deserialization would generally entail creating some kind of class/struct to hold the key/values from the json object. Now you have an object that you can add methods to.
Override the .Equals(), == operator and != operator functions of the object and provide the implementation details of comparing the two objects, ignoring the keys that are not important.
Some example code of overriding:
public class DateRange
{
public DateRange(DateTime start, DateTime end)
{
if (start>end)
{
throw new ArgumentException("Start date time cannot be after end date time");
}
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public static bool operator ==(DateRange range1, DateRange range2)
{
if (range1.Start == range2.Start && range1.End == range2.End)
{
return true;
}
return false;
}
public static bool operator !=(DateRange range1, DateRange range2)
{
return !(range1 == range2);
}
}
Upvotes: 1