c# - 如何在JSON.NET中实现自定义JsonConverter来反序列化基类对象的列表?

我试图扩展这里给出的json.net示例
http://james.newtonking.com/projects/json/help/CustomCreationConverter.html
我有另一个子类派生自基类/接口

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
    public string Department { get; set; }
    public string JobTitle { get; set; }
}

public class Artist : Person
{
    public string Skill { get; set; }
}

List<Person> people  = new List<Person>
{
    new Employee(),
    new Employee(),
    new Artist(),
};

如何反序列化以下JSON返回列表
[
  {
    "Department": "Department1",
    "JobTitle": "JobTitle1",
    "FirstName": "FirstName1",
    "LastName": "LastName1"
  },
  {
    "Department": "Department2",
    "JobTitle": "JobTitle2",
    "FirstName": "FirstName2",
    "LastName": "LastName2"
  },
  {
    "Skill": "Painter",
    "FirstName": "FirstName3",
    "LastName": "LastName3"
  }
]

我不想使用类型名处理JSonserializerSettings。我专门寻找定制的JSonConverter实现来处理这个问题。关于这方面的文档和示例在网络上非常稀少。我似乎无法在jsonConverter中获得重写的readjson()方法实现。


最佳答案:

使用标准CustomCreationConverter时,我正在努力研究如何生成正确的类型(PersonEmployee),因为为了确定这一点,您需要分析JSON,而使用Create方法没有内置的方法来实现这一点。
我找到了一个关于类型转换的讨论线程,结果提供了答案。这里有一个链接:Type converting
需要的是子类化JsonConverter,重写ReadJson方法,并创建一个接受Create的新抽象JObject方法。
jobject类提供了一种方法来加载JSON对象和
提供对此对象内数据的访问。
重写的ReadJson方法创建一个JObject并调用Create方法(由派生的converter类实现),传入JObject实例。
然后可以分析这个JObject实例,通过检查某些字段的存在性来确定正确的类型。
例子

string json = "[{
        \"Department\": \"Department1\",
        \"JobTitle\": \"JobTitle1\",
        \"FirstName\": \"FirstName1\",
        \"LastName\": \"LastName1\"
    },{
        \"Department\": \"Department2\",
        \"JobTitle\": \"JobTitle2\",
        \"FirstName\": \"FirstName2\",
        \"LastName\": \"LastName2\"
    },
        {\"Skill\": \"Painter\",
        \"FirstName\": \"FirstName3\",
        \"LastName\": \"LastName3\"
    }]";

List<Person> persons = 
    JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());

...

public class PersonConverter : JsonCreationConverter<Person>
{
    protected override Person Create(Type objectType, JObject jObject)
    {
        if (FieldExists("Skill", jObject))
        {
            return new Artist();
        }
        else if (FieldExists("Department", jObject))
        {
            return new Employee();
        }
        else
        {
            return new Person();
        }
    }

    private bool FieldExists(string fieldName, JObject jObject)
    {
        return jObject[fieldName] != null;
    }
}

public abstract class JsonCreationConverter<T> : JsonConverter
{
    /// <summary>
    /// Create an instance of objectType, based properties in the JSON object
    /// </summary>
    /// <param name="objectType">type of object expected</param>
    /// <param name="jObject">
    /// contents of JSON object that will be deserialized
    /// </param>
    /// <returns></returns>
    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, 
                                    Type objectType, 
                                     object existingValue, 
                                     JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

评论