在JSON.NET物业为基础的类型解析 [英] Property-based type resolution in JSON.NET
问题描述
是否可以覆盖使用JSON.NET基于JSON对象的属性类型解析?基于现有的API,它看起来像我需要接受 JsonPropertyCollection
并返回键入
来创建的一种方式。
Is it possible to override the type resolution using JSON.NET based on a property of the JSON object? Based on existing APIs, it looks like I need a way of accepting a JsonPropertyCollection
and returning the Type
to be created.
注:我知道的 TypeNameHandling属性的,但增加了一个 $类型
属性。我没有在源JSON控制。
NOTE: I'm aware of the TypeNameHandling attribute, but that adds a $type
property. I do not have control over the source JSON.
推荐答案
这样看来,这种处理通过创建一个自定义的<一个href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonConverter.htm">JsonConverter并将其添加到 JsonSerializerSettings.Converters
deserialisation之前。
It would appear that this is handled by creating a custom JsonConverter and adding it to JsonSerializerSettings.Converters
before deserialisation.
困惑留下了一个方便的样品上的JSON.NET讨论板中的codePLEX。我修改了样品定制返回键入
,并推迟到默认创建的机制,而不是当场创建对象实例。
nonplus has left a handy sample on the JSON.NET discussions board on Codeplex. I've modified the sample to return custom Type
and deferring to the default creation mechanism, rather than creating the object instance on the spot.
abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
protected abstract Type GetType(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
Type targetType = GetType(objectType, jObject);
// TODO: Change this to the Json.Net-built-in way of creating instances
object target = Activator.CreateInstance(targetType);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
这里是使用例子(还更新如上所述):
And here is the example usage (also updated as mentioned above):
class VehicleConverter : JsonCreationConverter<Vehicle>
{
protected override Type GetType(Type objectType, JObject jObject)
{
var type = (string)jObject.Property("Type");
switch (type)
{
case "Car":
return typeof(Car);
case "Bike":
return typeof(Bike);
}
throw new ApplicationException(String.Format(
"The given vehicle type {0} is not supported!", type));
}
}
这篇关于在JSON.NET物业为基础的类型解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!