第一个Json.Net Demo

 

 1  //序列化

 2       private void btnShow_Click(object sender, EventArgs e)

 3         {

 4             DataTable dt = new DataTable();

 5             DataColumn dcName = new DataColumn("Name");

 6             DataColumn dcAge = new DataColumn("Age");

 7             DataColumn dcCity = new DataColumn("City");

 8 

 9             dt.Columns.Add(dcName);

10             dt.Columns.Add(dcAge);

11             dt.Columns.Add(dcCity);

12             for (int i = 0; i < 10; i++)

13             {

14                 DataRow dr = dt.NewRow();

15                 dr[0] = "Name" + i;

16                 dr[1] = "Age" + i;

17                 dr[2] = "City" + i;

18                 dt.Rows.Add(dr);

19             }

20             string json = JsonConvert.SerializeObject(dt);

21             Console.WriteLine(json);

22             richTextBox1.Text = json;

23         }

24         //反序列化

25       private void button1_Click(object sender, EventArgs e)

26         {

27             string json = richTextBox1.Text;

28             DataTable dt1 = JsonConvert.DeserializeObject<DataTable>(json);

29             for (int i = 0; i < dt1.Rows.Count; i++)

30             {

31                 DataRow dr = dt1.Rows[i];

32                 Console.WriteLine("{0}\t{1}\t{2}\t", dr[0], dr[1], dr[2]);

33             }

34             dataGridView1.DataSource = dt1;

35         }

 

你可能感兴趣的:(.net)