I\'m seeing some weird behavior serializing with Json.NET v6.0.5 for objects that override the Equals method and have reference type properties, aside from string.
If you are implementing an override for bool Equals(object obj)
then you need to handle any type that might be passed to you. You cannot make the assumption that callers will always pass the type you are expecting. The usual solution is to do a simple type check before you cast, like this:
public override bool Equals(object obj)
{
if (obj is TypeYouAreExpecting)
{
TypeYouAreExpecting other = (TypeYouAreExpecting) obj;
bool areEqual = false;
// implement your equals logic here
return areEqual;
}
return base.Equals(obj);
}
If it is a third party library that throws an InvalidCastException
in the Equals
method, that is definitely a bug. I would contact the author and request that they fix it.
As for why Json.Net calls Equals
during serialization on objects of different types, this is done to check for reference loops. See Why does Json.Net call the Equals method on my objects when serializing? for more details.