抽象类或者接口:
public abstract class BaseFoo
{
public string FooBarBuzz { get; set; }
}
public class AFoo : BaseFoo
{
public string A { get; set; }
}
public class BFoo : BaseFoo
{
public string B { get; set; }
}
构造JSON内容
AFoo a = new AFoo();
a.FooBarBuzz = "A";
a.A = "Hello World";
BFoo b = new BFoo();
b.FooBarBuzz = "B";
b.B = "Hello World";
List<BaseFoo> allFoos = new List<BaseFoo>();
allFoos.Add(a);
allFoos.Add(b);
var result = JsonConvert.SerializeObject(allFoos);
结果值
异常代码:
var test = JsonConvert.DeserializeObject<List<BaseFoo>>(result);
问题
抽象类序列化失败
解决方案:
1.构造相应的转化类
注意ReadJson方法,根据不同的类型,进行不同的序列化
public class FooConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(BaseFoo));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo["FooBarBuzz"].Value<string>() == "A")
return jo.ToObject<AFoo>(serializer);
if (jo["FooBarBuzz"].Value<string>() == "B")
return jo.ToObject<BFoo>(serializer);
return null;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
2.使用
JsonConverter[] converters = { new FooConverter()};
var test = JsonConvert.DeserializeObject<List<BaseFoo>>(result, new JsonSerializerSettings() { Converters = converters });
引用:
1.英文原文
2.stackoverflow帖链接