1 回答
TA贡献1817条经验 获得超6个赞
除了您发现的问题之外,您当前的架构还有一些其他问题:
您忽略了记录在案的建议DefaultValueAttribute:
ADefaultValueAttribute不会导致成员使用属性值自动初始化。您必须在代码中设置初始值。
您当前的实现导致具有默认值的所有实例共享对数组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数组,而是使用条件属性序列化:
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在这里。
如果您决定使用DefaultValueHandling和DefaultValueAttribute用于数组,您将需要一个自定义合约解析器:
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();
并JsonSerializerSettings.ContractResolver在序列化时使用它:
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在这里。
笔记:
合约解析器仅适用于排名为 1 的数组。如果需要,您可以将其扩展到多维数组。
合约解析器在将默认值数组实例设置为成员时会自动克隆它,以避免上面提到的问题 #2。如果你不想这样,你可以删除ArrayDefaultValueProvider.
不清楚是否支持数组值默认值是 Json.NET 的预期功能。
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报