序列化时不会忽略在DefaultValue中声明的数组

时间:2019-01-06 22:53:29

标签: c# json.net

我正在使用JSON充当配置文件,并且我想要一个数组的默认值。我想让序列化的JSON忽略数组,如果它等于DefaultValueAttribute,那么,如果我在程序的第二版中决定更改DefaultValues,则将加载新的默认值,而不是未修改的JSON副本。原始默认值。

我的问题是,如果数组引用未更改,则代码有效,但是程序中的其他代码正在更改数组,但将值保留在其中。 (该程序维护该类的许多克隆,因此无法避免。)

这是使用c#交互式显示的问题:

using System.ComponentModel;
using Newtonsoft.Json;

class A
{
    [DefaultValue(new int[] { 4, 6, 12 })]
    public int[] SomeArray;
}

var serializerSettings = new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
};
var a = new A();
JsonConvert.PopulateObject("{}", a, serializerSettings);

Console.WriteLine(JsonConvert.SerializeObject(a, serializerSettings));
// Prints {}

a.SomeArray = new int[] { 4, 6, 12 };
Console.WriteLine(JsonConvert.SerializeObject(a, serializerSettings));
// Prints {"SomeArray":[4,6,12]}

如您所见,第一个SerializeObject可以工作,但是如果数组内容相同但数组引用不同,则会将默认值写到json中,这是我想避免的。

在这种情况下,有什么方法可以让Json.net忽略数组吗?

1 个答案:

答案 0 :(得分:3)

除了您发现的问题之外,当前的体系结构还存在其他一些问题:

  1. 您忽略了DefaultValueAttribute的{​​{3}}:

      

    DefaultValueAttribute不会导致成员使用属性值自动初始化。您必须在代码中设置初始值。

  2. 您当前的实现导致所有带有默认值的A实例共享对int[3] { 4, 6, 12 }数组的单个全局实例的引用。由于数组不是真正的只读数组,这意味着修改A的一个实例将使用默认值修改A的所有其他当前和将来的实例:

    var serializerSettings = new JsonSerializerSettings
    {
        DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
    };
    var a1 = JsonConvert.DeserializeObject<A>("{}", serializerSettings);
    // The following succeeds
    Assert.IsTrue(a1.SomeArray.SequenceEqual(new int[] { 4, 6, 12 }));
    
    // Sime SomeArray is a globally shared pointer, this will modify all current and future instances of A!
    a1.SomeArray[0] = -999;
    
    var a2 = JsonConvert.DeserializeObject<A>("{}", serializerSettings);
    // The following now fails!
    Assert.IsTrue(a2.SomeArray.SequenceEqual(new int[] { 4, 6, 12 }));
    

避免这些问题的最简单方法是根本不对阵列使用DefaultValueHandling,而应使用documented recommendations

class A
{
    static readonly int[] SomeArrayDefaultValue = new int[] { 4, 6, 12 };

    // Disable global settings for NullValueHandling and DefaultValueHandling
    [JsonProperty(NullValueHandling = NullValueHandling.Include, DefaultValueHandling = DefaultValueHandling.Include)]
    public int[] SomeArray = (int[])SomeArrayDefaultValue.Clone();

    public bool ShouldSerializeSomeArray()
    {
        return !(SomeArray != null && SomeArray.SequenceEqual(SomeArrayDefaultValue));
    }
}

演示小提琴#1 conditional property serialization

如果确定要对阵列使用DefaultValueHandlingDefaultValueAttribute,则需要here

public class ArrayDefaultValueContractResolver : DefaultContractResolver
{
    class ArrayDefaultValueProvider : IValueProvider
    {
        readonly IValueProvider baseProvider;
        readonly System.Array defaultValue;

        public ArrayDefaultValueProvider(IValueProvider baseProvider, System.Array defaultValue)
        {
            this.baseProvider = baseProvider;
            this.defaultValue = defaultValue;
        }

        #region IValueProvider Members

        public object GetValue(object target)
        {
            return baseProvider.GetValue(target);
        }

        public void SetValue(object target, object value)
        {
            // Make sure the default value is cloned since arrays are not truly read only.
            if (value != null && object.ReferenceEquals(value, defaultValue))
                value = defaultValue.Clone();
            baseProvider.SetValue(target, value);
        }

        #endregion
    }

    static void AddArrayDefaultHandling<T>(JsonProperty property)
    {
        var defaultValue = (T [])property.DefaultValue;

        // If the default value has length > 0, clone it when setting it back into the object.
        if (defaultValue.Length > 0)
        {
            property.ValueProvider = new ArrayDefaultValueProvider(property.ValueProvider, defaultValue);
        }

        // Add a ShouldSerialize method that checks for memberwise array equality.
        var valueProvider = property.ValueProvider;
        var oldShouldSerialize = property.ShouldSerialize;
        Predicate<object> shouldSerialize = target =>
            {
                var array = (T[])valueProvider.GetValue(target);
                return !(array == null || array.SequenceEqual(defaultValue));
            };
        if (oldShouldSerialize == null)
            property.ShouldSerialize = shouldSerialize;
        else
            property.ShouldSerialize = (target) => shouldSerialize(target) && oldShouldSerialize(target);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.PropertyType.IsArray && property.DefaultValue != null && property.DefaultValue.GetType() == property.PropertyType
            && property.PropertyType.GetArrayRank() == 1)
        {
            typeof(ArrayDefaultValueContractResolver)
                .GetMethod("AddArrayDefaultHandling", BindingFlags.Static | BindingFlags.NonPublic)
                .MakeGenericMethod(property.PropertyType.GetElementType())
                .Invoke(null, BindingFlags.Static | BindingFlags.NonPublic, null, new [] { property }, null);
        }
        return property;
    }
}

要使用它,请将静态实例缓存在某处以提高性能,例如

static IContractResolver resolver = new ArrayDefaultValueContractResolver();

并在序列化时将其用作custom contract resolver

var serializerSettings = new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
    ContractResolver = resolver,
};
var a = new A();
JsonConvert.PopulateObject("{}", a, serializerSettings);

Console.WriteLine(JsonConvert.SerializeObject(a, serializerSettings));
Assert.IsTrue(JsonConvert.SerializeObject(a, serializerSettings) == "{}");

a.SomeArray = new int[] { 4, 6, 12 };
Console.WriteLine(JsonConvert.SerializeObject(a, serializerSettings));
Assert.IsTrue(JsonConvert.SerializeObject(a, serializerSettings) == "{}");

演示小提琴#2 JsonSerializerSettings.ContractResolver

注意:

  • 合同解析器仅适用于排名为1的数组。您可以根据需要将其扩展到多维数组。

  • 合同解析器将默认值数组实例设置为成员时会自动克隆该默认值数组实例,以避免上述问题2。如果您不希望这样做,可以删除ArrayDefaultValueProvider

  • 目前还不清楚Json.NET是否支持对数组值的默认值。