How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

前端 未结 9 1800
星月不相逢
星月不相逢 2020-11-21 05:07

I am trying to extend the JSON.net example given here http://james.newtonking.com/projects/json/help/CustomCreationConverter.html

I have another sub class deriving

9条回答
  •  粉色の甜心
    2020-11-21 06:06

    The project JsonSubTypes implement a generic converter that handle this feature with the helps of attributes.

    For the concrete sample provided here is how it works:

        [JsonConverter(typeof(JsonSubtypes))]
        [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
        [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
        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; }
        }
    
        [TestMethod]
        public void Demo()
        {
            string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                          "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                          "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";
    
    
            var persons = JsonConvert.DeserializeObject>(json);
            Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);
        }
    

提交回复
热议问题