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!
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With