JSON.NET中基于属性的类型解析

本文关键字:类型 属性 NET 于属性 JSON | 更新日期: 2023-09-27 18:05:03

是否可以使用JSON覆盖类型解析?. NET基于JSON对象的属性?基于现有的api,看起来我需要一种接受JsonPropertyCollection并返回要创建的Type的方法。

注意:我知道TypeNameHandling属性,但它增加了一个$type属性。我无法控制源JSON

JSON.NET中基于属性的类型解析

这似乎是通过创建自定义JsonConverter并在反序列化之前将其添加到JsonSerializerSettings.Converters来处理的。

nonplus在JSON中留下了一个方便的示例。. NET讨论板上的Codeplex。我已经修改了示例以返回自定义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;
    }
}

下面是示例用法(也按照上面提到的更新):

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));
    }
}