【发布时间】:2014-09-01 03:26:00
【问题描述】:
我有以下类,用作字典中的键:
public class MyClass
{
private readonly string _property;
public MyClass(string property)
{
_property = property;
}
public string Property
{
get { return _property; }
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return _property == other._property;
}
public override int GetHashCode()
{
return _property.GetHashCode();
}
}
我正在运行的测试在这里:
[Test]
public void SerializeDictionaryWithCustomKeys()
{
IDictionary<MyClass, object> expected = new Dictionary<MyClass, object>();
expected.Add(new MyClass("sth"), 5.2);
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string output = JsonConvert.SerializeObject(expected, Formatting.Indented, jsonSerializerSettings);
var actual = JsonConvert.DeserializeObject<IDictionary<MyClass, object>>(output, jsonSerializerSettings);
CollectionAssert.AreEqual(expected, actual);
}
测试失败,因为 Json.Net 似乎在字典键上使用了ToString() 方法,而不是正确地序列化它们。上面测试的结果 json 是:
{
"$type": "System.Collections.Generic.Dictionary`2[[RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass, RiskAnalytics.UnitTests],[System.Object, mscorlib]], mscorlib",
"RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass": 5.2
}
这显然是错误的。我怎样才能让它工作?
【问题讨论】:
-
JSON 并不总是能很好地处理字典,为什么不直接覆盖
MyClass的.ToString()? -
为什么字典键这么复杂?为什么在你的类中没有字典值,然后用列表替换字典?
-
你能指定预期的输出应该是什么样子吗?因为我很确定复杂的属性名称不是 JSON 的一部分...
-
@TMcKeown,在实际代码中有不同类型的键。我可以在所有这些上实现
ToString()和相应的类型转换器,但我希望序列化程序能为我完成这项工作...... -
@mason,显然不是。