JSON.NET Serialization - How does DefaultReferenceResolver compare equality?

前端 未结 2 1265
醉话见心
醉话见心 2021-01-06 08:10

I am using JSON.NET 6.0.3. I have changed PreserveReferences option as follows:

HttpConfiguration.Formatters.JsonFormatter.SerializerSettings.Pre         


        
2条回答
  •  失恋的感觉
    2021-01-06 08:37

    Json.Net will call the Equals method on the objects being compared. In certain scenarios you may not want this however for example when it is checking for circular references it does the same whereas it may be more ideal to check for reference equality. They do this however to give the developer full control by overridding the Equals method in their classes.

    You can override the default implementation. For example to make this a reference equality you would do the following:

    var settings = new JsonSerializerSettings
                               {
                                   EqualityComparer = new DefaultEqualityComparer(),
                               };
    
    public class DefaultEqualityComparer : IEqualityComparer
        {
            public bool Equals(object x, object y)
            {
                return ReferenceEquals(x, y);
            }
    
            public int GetHashCode(object obj)
            {
                return obj.GetHashCode();
            }
        }
    

提交回复
热议问题