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

Posted laughatselfswrong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ());

 

效果:

技术图片

 

以上是关于C#-Json-抽象类的反序列化的主要内容,如果未能解决你的问题,请参考以下文章

JSON中的反序列化和序列化是啥?

Newtonsoft.Json 处理多态类型的反序列化

包装的 json 属性的反序列化

WCF REST Web 服务 - Json 的反序列化

C#动态实体集的反序列化(动态JSON反序列化)

Gson关于抽象类的序列化与反序列化