C#-Json-抽象类的反序列化

引用:

1 using System;
2 using System.Collections.Generic;
3 using Newtonsoft.Json;
4 using Newtonsoft.Json.Linq;

自定义转化器:

 1    public class JsonPersonConverter : JsonConverter
 2    {
 3        public override bool CanConvert (Type objectType)
 4        {
 5            return typeof (Person).IsAssignableFrom (objectType);
 6        }
 7 
 8        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 9        {
10            var jsonObject = JObject.Load (reader);
11            object target = null;
12            JToken gender;
13            if (jsonObject.TryGetValue ("Gender", out gender))
14            {
15                switch (gender.ToString ())
16                {
17                    case "man":
18                        target = new Man ();
19                        break;
20                    case "woman":
21                        target = new Woman ();
22                        break;
23                }
24            }
25            serializer.Populate (jsonObject.CreateReader (), target);
26            return target;
27        }
28 
29        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
30        {
31            throw new NotImplementedException ();
32        }
33    }
34 
35    public abstract class Person
36    {
37        public string Gender { get; set; }
38    }
39 
40    public class Man : Person
41    {
42        public string Power { get; set; }
43    }
44 
45    public class Woman : Person
46    {
47        public string Skirt { get; set; }
48    }

 

调用:

1    var json = JsonConvert.SerializeObject (new List<Person> ()
2    {
3        new Man { Gender = "man", Power = "power" },
4        new Woman { Gender = "woman", Skirt = "skirt" }
5    });
6    var people = JsonConvert.DeserializeObject<List<Person>> (json, new JsonPersonConverter ());

 

效果:

 

posted @ 2019-09-11 08:58  自笑非  阅读(1444)  评论(0编辑  收藏  举报