JSON.NET序列化继承对象
之前使用JSON.NET简单序列化了对象…
现在来读序列化文件…
static void Main(string[] args)
{
List<BaseTest> baselist = new List<BaseTest>();
childTest ct = new childTest();
ct.n = 0;
ct.f = 1.234f;
baselist.Add(ct);
OtherTest ot = new OtherTest();
ot.n = 0;
ot.strList.Add("ot1");
ot.strList.Add("ot2");
baselist.Add(ot);
try
{
string str = Newtonsoft.Json.JsonConvert.SerializeObject(baselist);
Console.WriteLine(str);
List<BaseTest> p = (List<BaseTest>)Newtonsoft.Json.JsonConvert.DeserializeObject<List<BaseTest>>(str);
}
catch (Exception e)
{
System.Diagnostics.Debug.Assert(false);
}
Console.ReadKey();
}
结果发现,读取道德序列化,全是基类的信息…
由序列化出来的字符串也可以看出来,本身序列化也没有附带类型信息…
经过查阅API接口…得知,需要改成如下代码…
static void Main(string[] args)
{
List<BaseTest> baselist = new List<BaseTest>();
childTest ct = new childTest();
ct.n = 0;
ct.f = 1.234f;
baselist.Add(ct);
OtherTest ot = new OtherTest();
ot.n = 0;
ot.strList.Add("ot1");
ot.strList.Add("ot2");
baselist.Add(ot);
try
{
Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
jsonSerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All;
string str = Newtonsoft.Json.JsonConvert.SerializeObject(baselist, jsonSerializerSettings);
Console.WriteLine(str);
List<BaseTest> p = (List<BaseTest>)Newtonsoft.Json.JsonConvert.DeserializeObject<List<BaseTest>>(str, jsonSerializerSettings);
}
catch (Exception e)
{
System.Diagnostics.Debug.Assert(false);
}
Console.ReadKey();
}
此时,序列化的结果已经变成了
{"$type":"System.Collections.Generic.List`1[[ConsoleApplication1.BaseTest, ConsoleApplication1]], mscorlib","$values":[{"$type":"ConsoleApplication1.childTest, ConsoleApplication1","f":1.234,"n":0},{"$type":"ConsoleApplication1.OtherTest, ConsoleApplication1","strList":{"$type":"System.Collections.Generic.List`1[[System.String, mscorlib]], mscorlib","$values":["ot1","ot2"]},"n":0}]}
可以看出,此时已经附带了类型信息…已经可以正常序列化子类对象了…