c# Json 自定义类作为字典键时,序列化和反序列化的处理方法

时间:2023-03-08 15:49:18
c# Json 自定义类作为字典键时,序列化和反序列化的处理方法

一般情况下,Newtonsoft.Json.dll 对 Dictionary<int,object>、Dictionary<string,object>等序列化与反序列化都是成功的,但是使用自定义类作为键,则会报错,如下图

c# Json 自定义类作为字典键时,序列化和反序列化的处理方法

处理办法代码所示:

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);
}
}

c# Json 自定义类作为字典键时,序列化和反序列化的处理方法