1

How to ignore casing when using JTokenEqualityComparer?

        JTokenEqualityComparer comp = new JTokenEqualityComparer();

        // arrange
        var obj1 = new JObject();
        obj1.Add("First Name", "foo");
        obj1.Add("Last Name", "bar");

        var obj2 = new JObject();
        obj2.Add("First Name", "Foo");
        obj2.Add("Last Name", "Bar");


        // act
        var hashCode1 = comp.GetHashCode(obj1);
        var hashCode2 = comp.GetHashCode(obj2);


        // assert            
        Assert.Equal(hashCode1, hashCode2);

Update 1
I want to compare two JObjects. The objects may be deep complex object. JToken has static method DeepEquals that compares two deep objects. However i want to get unique hash value and store that value in the SQL database. So sql procedures can also do comparison.

from SO

I did see that they have an internal method called GetDeepHashCode but the implementation is based on other protected properties and therefore, I cannot "copy" the code and create an extension method from it

and solution is

You can use JTokenEqualityComparer.GetHashCode(JToken token) for this purpose. It provides access to the GetDeepHashCode() method you saw.

LP13
  • 30,567
  • 53
  • 217
  • 400
  • That class only works with JToken objects, see https://stackoverflow.com/questions/49886411/json-net-jtoken-keys-are-case-sensitive?noredirect=1&lq=1 for an alternate way. – Jay Jun 20 '19 at 15:36
  • JObject is derived from JToken. That why i was able to pass JObject to GetHashCode method – LP13 Jun 20 '19 at 15:39
  • Right, but the methods you need are on JObject, you may be able to achieve it getting all the keys of each object but the syntax your looking for is something like this `var jObject = JToken.Load(reader) as JObject; JToken foo; jObject.TryGetValue("foo", StringComparison.OrdinalIgnoreCase, out foo);` – Jay Jun 20 '19 at 15:41
  • 1
    To do it all in the JTokenEqualityComparer you would need to derive and do something like https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_Linq_JToken_SelectTokens.htm SelectTokens on each to compare the keys in the way you wanted – Jay Jun 20 '19 at 15:43
  • See also https://stackoverflow.com/questions/12055743/json-net-jobject-key-comparison-case-insensitive – Jay Jun 20 '19 at 15:45
  • i am not sure converting to dictionary would solve my issue. See my update 1 – LP13 Jun 20 '19 at 15:55

0 Answers0