我有下面的類,我在一本字典的主要用途:如何使用Json.Net使用自定義鍵序列化/反序列化字典?
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()'? –
爲什麼這麼複雜的字典鍵?爲什麼不在你的類裏面有字典值,然後用列表替換字典? – gunr2171
你能指定預期輸出應該是什麼樣子嗎?因爲我非常肯定,複雜的屬性名稱不是JSON的一部分...... – Grx70