c# - 当对象实现 Equals 时,Newtonsoft.Json 序列化表现得很奇怪

标签 c# json serialization json.net

我有以下示例。

 public class Main
 {
     public Student Student { get; set; }
     public override bool Equals(object obj)
     {
         if (this.GetType() != obj.GetType()) throw new Exception();
         return Student.Age == ((Student)obj).Age;
     }
 }

 public class Student
 {
     public int Age { get; set; }
     public Name Name { get; set; }

     public override bool Equals(object obj)
     {
         if (this.GetType() != obj.GetType()) throw new Exception();
         return Age == ((Student)obj).Age;
     }
 }

 public class Name
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public override bool Equals(object obj)
     {
         if (this.GetType() != obj.GetType()) throw new Exception();
         return FirstName == ((Name)obj).FirstName && LastName == ((Name)obj).LastName;
     }
 }

当我尝试序列化

JsonConvert.SerializeObject(new Main{ ... });

我在 Main 类型的 Equals 方法中得到不同的类型,并且我会在其他 Equals 方法中假设不同的类型。

我得到的类型是,对于

this.GetType() // => Main 
obj.GetType() // => Student

为什么 json 会这样做,为什么它使用 Equals 方法以及如何让它表现得像它应该的那样?

最佳答案

在不同对象类型之间进行比较最终是有效的(即使不常见)。答案应该是“否”(false)。所以:

public override bool Equals(object obj)
    => obj is Main other && Equals(Student, other.Student);

public override bool Equals(object obj)
    => obj is Student other && Age == other.Age; // && Equals(Name, other.Name) ?

public override bool Equals(object obj)
    => obj is Name other && FirstName == other.FirstName && LastName == other.LastName;

(或类似的东西,取决于你想要什么)。

但是!您应该始终确保 GetHashCode()Equals() 兼容,否则相等性未完全实现(请参阅 CS0659)

关于c# - 当对象实现 Equals 时,Newtonsoft.Json 序列化表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53596933/

相关文章:

c# - 进入外部应用程序的消息循环

c# - NLP:提取形状名称和形状尺寸

hadoop - 在Spark中读取级联序列文件

c# - XML XNA 对象反序列化

javascript - 我们如何在不同选项卡上序列化 selectpicker 插件文本?

c# - 用 esc 关闭 mdi child

c# - 从 SQLite 数据库 C# WPF 中提取 DateTime 的问题

java - 使用Swagger注解记录数组类型的请求体

java - Spring + Jackson 不支持内容类型 'application/json;charset=UTF-8'

java - 使用任意键将 JSON 反序列化为 Map