【发布时间】:2014-10-24 16:20:28
【问题描述】:
我看到使用 Json.NET v6.0.5 对覆盖 Equals 方法并具有引用类型属性(字符串除外)的对象进行序列化时出现了一些奇怪的行为。
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
{
}
然后我序列化它。
var testObj = new TestObject() { CustomTypeProperty = new ChildObject(), IntProperty = 1, ListCustomProperty = new List<ChildObject>(), ListProperty = new List<string>(), StringProperty = "abc" };
var json = JsonConvert.SerializeObject(testObj);
我可以看到它调用了 TestObject.Equals(object obj) 3 次,传入的不是 TestObject,而是 CustomTypePropety 对象,然后是 ListProperty,然后是 ListCustomProperty。在我的情况下,这会导致 InvalidCastException,因为 TestObject 尝试将 obj 参数转换为 TestObject。我无法在实际场景中更改此设置,因为该类型位于第三方库中。
这是 Json.NET 中的错误还是我做错了什么?我已经挖掘了一段时间,找不到任何解决方案。感谢您的帮助。
编辑
我刚刚升级到 Json.NET 6.0.6 并看到了相同的行为。
【问题讨论】:
标签: c# serialization json.net