Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class BaseTest
{
    public int n;

    public BaseTest()
    {
        n = 0;
    }
}

static void Main(string[] args)
{
    BaseTest bt = new BaseTest();
    bt.n = 1;
    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(bt));

    Console.ReadKey();
}

输出

1
{"n":1}

当类有继承关系的时候…

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class BaseTest
{
    public int n;

    public BaseTest()
    {
        n = 0;
    }
}

class childTest : BaseTest
{
    public float f;

    public childTest()
        : base()
    {
        f = 1.23f;
    }
}

class OtherTest : BaseTest
{
    public List<string> strList;

    public OtherTest()
        : base()
    {
        strList = new List<string>();
    }
}

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
    {
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(baselist));      
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.Assert(false);
    }
    Console.ReadKey();
}

输出

1
[{"f":1.234,"n":0},{"strList":["ot1","ot2"],"n":0}]