之前使用JSON.NET简单序列化了对象…

现在来读序列化文件…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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接口…得知,需要改成如下代码…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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();
}

此时,序列化的结果已经变成了

1
{"$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}]}

可以看出,此时已经附带了类型信息…已经可以正常序列化子类对象了…