我有以下课程,将其用作字典中的键:
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是:
ToString()
{ "$type": "System.Collections.Generic.Dictionary`2[[RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass, RiskAnalytics.UnitTests],[System.Object, mscorlib]], mscorlib", "RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass": 5.2 }
这显然是错误的。我如何使它工作?
这应该可以解决问题:
序列化:
JsonConvert.SerializeObject(expected.ToArray(), Formatting.Indented, jsonSerializerSettings);
通过调用,expected.ToArray()您正在序列化一个KeyValuePair<MyClass, object>对象数组而不是字典。
expected.ToArray()
KeyValuePair<MyClass, object>
反序列化:
JsonConvert.DeserializeObject<KeyValuePair<IDataKey, object>[]>(output, jsonSerializerSettings).ToDictionary(kv => kv.Key, kv => kv.Value);
在这里,您可以反序列化数组,然后通过.ToDictionary(...)调用检索字典。
.ToDictionary(...)
我不确定输出是否满足您的期望,但肯定可以通过相等性断言。