I'm trying to implement a cache for JObjects
.
I was surprised to see that they didn't override the GetHashCode
method and therefore, I can't use it as a unique key.
Since my json's are pretty large, I don't want to use JObject.ToString().GetHashCode
as a solution.
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.
I also don't want to use reflection and invoke the internal GetDeepHashCode
method.
I'm looking for a way to create a unique cache key for a JObject
and I don't want the method to be extra expensive when it comes to performance.
If you use eclipse, you can generate equals() and hashCode() using: Source -> Generate hashCode() and equals(). Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.
No it is not unique. GetHashCode returns an Integer which has 2^32 possible values. However, there are clearly more than 2^32 strings that you could possibly construct. This guarantees that it cannot be unique.
GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes.
Returns. A 32-bit signed integer hash code.
You can use JTokenEqualityComparer.GetHashCode(JToken token)
for this purpose. It provides access to the GetDeepHashCode()
method you saw.
var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);
Note that JTokenEqualityComparer.Equals(JToken x, JToken y)
calls JToken.DeepEquals()
(source) so this comparer is suited for use as an IEqualityComparer<JToken>
when constructing hash tables or dictionaries of LINQ-to-JSON objects and uniqueness of values is desired.
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