Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two JSON ignoring certain keys in C#?

Tags:

json

c#

json.net

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!

like image 495
John Mcdock Avatar asked Nov 01 '22 08:11

John Mcdock


1 Answers

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);
    }
}
like image 95
C Bauer Avatar answered Nov 15 '22 07:11

C Bauer