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

2021-02-03 15:16

阅读:342

标签:creat   ide   tin   iter   newton   mamicode   people   bsp   switch   

引用:

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 ()
2    {
3        new Man { Gender = "man", Power = "power" },
4        new Woman { Gender = "woman", Skirt = "skirt" }
5    });
6    var people = JsonConvert.DeserializeObject> (json, new JsonPersonConverter ());

 

效果:

技术图片

 

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

标签:creat   ide   tin   iter   newton   mamicode   people   bsp   switch   

原文地址:https://www.cnblogs.com/LaughAtSelfsWrong/p/11504271.html


评论


亲,登录后才可以留言!