使用 Json.NET,我想将 a 映射JObject到具有以下行为的 .NET 对象:
对于 的(非空)数组属性JObject,替换目标对象上的整个集合。
对于 的(非空)对象属性JObject,如果目标对象的属性不为空,则重用目标对象的属性,并仅将提供的属性映射到其上。
JsonSerializer.Populate似乎是我想要的,如这个答案中所述。至于我正在寻找的行为,似乎我可以通过JsonSerializerSettings.ObjectCreationHandling实现其中之一,但不能同时实现两者。ObjectCreationHandling.Replace执行我想要的关于要求 #1 的操作,同时ObjectCreationHandling.Auto执行我想要的关于要求 #2 的操作,但它将数组项附加到现有集合中。
这里推荐的实现这两个要求的方法是什么?
Json.NET 将自动替换任何数组或只读集合。要在反序列化时清除读写集合,您可以创建一个自定义契约解析器,该解析器向每个可修改的集合添加一个OnDeserializingCallback,以便在反序列化开始时清除该集合。清除集合而不是直接替换它可以处理集合仅获取的情况,例如:
public class RootObject
{
readonly HashSet<int> hashSet = new HashSet<int>();
public HashSet<int> HashSetValues { get { return this.hashSet; } }
}
Run Code Online (Sandbox Code Playgroud)
合约解析器如下:
public class CollectionClearingContractResolver : DefaultContractResolver
{
static void ClearGenericCollectionCallback<T>(object o, StreamingContext c)
{
var collection = o as ICollection<T>;
if (collection == null || collection is Array || collection.IsReadOnly)
return;
collection.Clear();
}
static SerializationCallback ClearListCallback = (o, c) =>
{
var collection = o as IList;
if (collection == null || collection is Array || collection.IsReadOnly)
return;
collection.Clear();
};
protected override JsonArrayContract CreateArrayContract(Type objectType)
{
var contract = base.CreateArrayContract(objectType);
if (!objectType.IsArray)
{
if (typeof(IList).IsAssignableFrom(objectType))
{
contract.OnDeserializingCallbacks.Add(ClearListCallback);
}
else if (objectType.GetCollectItemTypes().Count() == 1)
{
MethodInfo method = typeof(CollectionClearingContractResolver).GetMethod("ClearGenericCollectionCallback", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
MethodInfo generic = method.MakeGenericMethod(contract.CollectionItemType);
contract.OnDeserializingCallbacks.Add((SerializationCallback)Delegate.CreateDelegate(typeof(SerializationCallback), generic));
}
}
return contract;
}
}
public static class TypeExtensions
{
public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
{
if (type == null)
throw new ArgumentNullException();
if (type.IsInterface)
return new[] { type }.Concat(type.GetInterfaces());
else
return type.GetInterfaces();
}
public static IEnumerable<Type> GetCollectItemTypes(this Type type)
{
foreach (Type intType in type.GetInterfacesAndSelf())
{
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
yield return intType.GetGenericArguments()[0];
}
}
}
}
public static class JsonExtensions
{
public static void Populate<T>(this JToken value, T target) where T : class
{
value.Populate(target, null);
}
public static void Populate<T>(this JToken value, T target, JsonSerializerSettings settings) where T : class
{
using (var sr = value.CreateReader())
{
JsonSerializer.CreateDefault(settings).Populate(sr, target);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后要使用它,请执行以下操作:
var settings = new JsonSerializerSettings
{
ContractResolver = new CollectionClearingContractResolver(),
};
jObject.Populate(rootObject, settings);
Run Code Online (Sandbox Code Playgroud)
小提琴样本。
当反序列化在默认构造函数中填充集合的对象时,这样的契约解析器也很有用,如反序列化会导致 List-Entries 的副本。