JsonConvert.SerializeObject passes custom type properties to parent types Equals(object) method

前端 未结 1 1603
鱼传尺愫
鱼传尺愫 2021-01-21 10:33

I\'m seeing some weird behavior serializing with Json.NET v6.0.5 for objects that override the Equals method and have reference type properties, aside from string.



        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 11:12

    If you are implementing an override for bool Equals(object obj) then you need to handle any type that might be passed to you. You cannot make the assumption that callers will always pass the type you are expecting. The usual solution is to do a simple type check before you cast, like this:

    public override bool Equals(object obj)
    {
        if (obj is TypeYouAreExpecting)
        {
            TypeYouAreExpecting other = (TypeYouAreExpecting) obj;
            bool areEqual = false;
    
            // implement your equals logic here
    
            return areEqual;
        }
    
        return base.Equals(obj);
    }
    

    If it is a third party library that throws an InvalidCastException in the Equals method, that is definitely a bug. I would contact the author and request that they fix it.

    As for why Json.Net calls Equals during serialization on objects of different types, this is done to check for reference loops. See Why does Json.Net call the Equals method on my objects when serializing? for more details.

    0 讨论(0)
提交回复
热议问题