是否可以使用JSON.NET基于JSON对象的属性覆盖类型解析?基于现有的API,看起来我需要一种接受JsonPropertyCollection并返回Type要创建的方法.
注意:我知道TypeNameHandling属性,但它添加了一个$type属性.我无法控制源JSON.
Ric*_*lay 14
看起来这是通过创建自定义JsonConverter并JsonSerializerSettings.Converters在反序列化之前添加它来处理的.
nonplus在Codeplex 的JSON.NET讨论板上留下了一个方便的样本.我已经修改了示例以返回自定义Type并推迟到默认创建机制,而不是在现场创建对象实例.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是示例用法(也如上所述更新):
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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7514 次 |
| 最近记录: |