一般情况下,Newtonsoft.Json.dll 对
Dictionary<int,object>、Dictionary<string,object>等序列化与反序列化都是成功的,但是使用自定义类作为键,则会报错,如下图
处理办法代码所示:
public class TestClass
{
public string Name = "";
public TestClass(string n)
{
Name = n;
}
public override bool Equals(object obj)
{
TestClass other = obj as TestClass;
if (other == null)
return false; if (!base.GetType().Equals(obj.GetType()))
return false; return (this.Name.Equals(other.Name));
} public override int GetHashCode() //重要
{
return Name.GetHashCode();
}
public static explicit operator TestClass(string jsonString)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(jsonString);
} public override string ToString() //重要
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
}