一般情况下,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 自定义类作为字典键时,序列化和反序列化的处理方法

 

相关文章:

  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2021-08-31
  • 2022-12-23
  • 2021-09-03
  • 2022-01-19
  • 2021-10-11
猜你喜欢
  • 2021-09-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2021-07-06
  • 2022-02-26
  • 2021-11-08
相关资源
相似解决方案