为什么序列化时Json.Net会在我的对象上调用Equals方法? [英] Why does Json.Net call the Equals method on my objects when serializing?

查看:116
本文介绍了为什么序列化时Json.Net会在我的对象上调用Equals方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Newtonsoft.Json SerializeObject方法时遇到了一个错误.在此处之前已被询问. ,但是与Newtonsoft一起工作的人们没有得到答案.

I just ran into an error when I was using the Newtonsoft.Json SerializeObject method. It has been asked before here, but there was no answer from the people working with Newtonsoft as to why this happens.

基本上,当像这样调用SerializeObject时:

Basically, when calling SerializeObject like this:

string json = Newtonsoft.Json.JsonConvert.SerializeObject(from, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

在很多我在类中重写的Equals方法中出现错误:

I get errors in a lot of Equals methods I have overridden in my classes:

public override bool Equals(object obj)
{
    if (obj == null)
        return false;

    CapacityConfiguration cc = (CapacityConfiguration)obj; // <-- TypeCastException here; other Properties of the same class are sent in as parameter!
}

当然,通过这样的检查,我意识到可以很容易地对其进行修复:

And of course I realize that it's "easy" to fix, by checking like this:

public override bool Equals(object obj)
{
    if (obj is CapacityConfiguration == false)
        return false;

    CapacityConfiguration cc = (CapacityConfiguration)obj;
}

但是真正的问题是: Json.Net为什么要在该类的Equals方法中发送其他类型的对象?更具体地说,Json.Net似乎在该类中发送了许多其他属性,而不是另一个相同类型的对象.

But the real question is: Why does Json.Net send in other types of objects in the Equals method of the class? More specifically, Json.Net seems to send in a lot of other properties in the class, instead of another object of the same type.

对我来说,这很奇怪.任何输入将不胜感激.

To me, it's completely weird. Any input would be appreciated.

根据Visual Studio,我正在使用"8.0.0.0版".

I am using "Version 8.0.0.0" according to Visual Studio.

更新1

易于测试,因为它具有可重复性:

It's easy to test, as it is reproducible:

public class JsonTestClass
{
    public string Name { get; set; }
    public List<int> MyIntList { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        JsonTestClass jtc = (JsonTestClass)obj;
        return true;
    }
}

然后将这段代码放在Program.cs或其他任何地方:

And then just place this code in Program.cs or anywhere else:

JsonTestClass c = new JsonTestClass();
c.Name = "test";
c.MyIntList = new List<int>();
c.MyIntList.Add(1);

string json = Newtonsoft.Json.JsonConvert.SerializeObject(c, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

,您将收到TypeCast异常:

and you will get the TypeCast Exception:

推荐答案

为什么JsonConvert.SerializeObject调用object.Equals方法?

由于使用JsonConvert.SerializeObject时,有一种方法 CheckForCircularReference ,它被用来检查属性是否重新引用了您自己的对象,从而导致无限循环.

Because when you use JsonConvert.SerializeObject, there is a method CheckForCircularReference which is called to check whether a property re-references your own object, leading to an infinite loop.

 private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)

CheckForCircularReference方法中,部分代码使用Contains方法,如果您的object未实现IEquatable<T>接口,它将调用object.Equals.

In the CheckForCircularReference method, part of code uses the Contains method, which will call object.Equals if your object didn't implement the IEquatable<T> interface.

bool exists = (Serializer._equalityComparer != null)
                ? _serializeStack.Contains(value, Serializer._equalityComparer)
                : _serializeStack.Contains(value);

说明

  1. _serializeStack是当前正在序列化的对象的列表.
  2. List<T>.Contains方法检查集合中是否包含当前属性.
  3. List<T>.Contains使用EqualityComparer<T>.Default,如果类型实现,则使用IEquatable<T>,否则使用object.Equals.
  4. object value参数是您当前的Property对象.
  1. _serializeStack is a list of objects currently being serialized.
  2. The List<T>.Contains method checks whether the current property is or isn't contained in the collection.
  3. List<T>.Contains uses EqualityComparer<T>.Default, which in turn uses IEquatable<T> if the type implements it, or object.Equals otherwise.
  4. The object value parameter is your current Property object.


这是一个自引用循环的示例:

public class JsonTestClass
{
    public string Name { get; set; }
    public List<int> MyIntList { get; set; }
    public JsonTestClass Test{get;set;}
    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        JsonTestClass jtc = (JsonTestClass)obj;
        return true;
   }
}

JsonTestClass c = new JsonTestClass();
c.Name = "test";
c.Test = c;
string json = JsonConvert.SerializeObject
               (c, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

我们将得到一个例外:

为类型为"Program + JsonTestClass"的属性"test"检测到自引用循环.路径.

Self referencing loop detected for property 'test' with type 'Program+JsonTestClass'. Path ''.

但是,如果我们这样做,就不会出现错误:

But if we do it like this there is no error:

JsonTestClass c = new JsonTestClass();
c.Name = "test";
c.Test = new JsonTestClass();

string json = JsonConvert.SerializeObject
       (c, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

这篇关于为什么序列化时Json.Net会在我的对象上调用Equals方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆