码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2019-09-11 09:47:43      阅读:433      评论:0      收藏:0      [点我收藏+]

标签: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<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 ());

 

效果:

技术图片

 

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!