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.
public class TestObject
{
public ChildObject CustomTypeProperty
{
get;
set;
}
public List<string> ListProperty
{
get;
set;
}
public List<ChildObject> ListCustomProperty
{
get;
set;
}
public string StringProperty
{
get;
set;
}
public int IntProperty
{
get;
set;
}
public override bool Equals(object obj)
{
Console.WriteLine(obj.GetType().FullName);
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class ChildObject
{
}
Then I serialize it.
var testObj = new TestObject() { CustomTypeProperty = new ChildObject(), IntProperty = 1, ListCustomProperty = new List<ChildObject>(), ListProperty = new List<string>(), StringProperty = "abc" };
var json = JsonConvert.SerializeObject(testObj);
I can see that it calls TestObject.Equals(object obj) three times and passes in not the TestObject, but the CustomTypePropety object, then the ListProperty and then the ListCustomProperty. In my case this causes an InvalidCastException because TestObject tries to cast the obj parameter to a TestObject. I cannot change this in the real-world scenario because the the type is in a third party library.
Is this a bug in Json.NET or am I doing something wrong? I've been digging for a while and cannot find any resolution. Thanks for the help.
EDIT
I just upgraded to Json.NET 6.0.6 and saw the same behavior.