Newtonsoft.Json 与 DataTable的相互转换

时间:2021-09-10 20:38:40

 

1.这里下载:http://www.newtonsoft.com/products/json/ 

安装: 
   解压下载文件,得到Newtonsoft.Json.dll 
   在项目中添加引用 
2.引入命名空间 

创建一个DataTable对象:

DataTable dt = new DataTable();
        DataColumn dcName = new DataColumn("Name"); DataColumn dcAge = new DataColumn("Age"); DataColumn dcCity = new DataColumn("City"); dt.Columns.Add(dcName); dt.Columns.Add(dcAge); dt.Columns.Add(dcCity); for (int i = 0; i < 10; i++) { DataRow dr = dt.NewRow(); dr[0] = "Name" + i; dr[1] = "Age" + i; dr[2] = "City" + i; dt.Rows.Add(dr); }

 转换为json格式:

string json = JsonConvert.SerializeObject(dt);
Console.WriteLine(json);

json格式转换为DataTable:

 DataTable dt1 = JsonConvert.DeserializeObject<DataTable>(json);
 for (int i = 0; i < dt1.Rows.Count; i++)
 {
     DataRow dr = dt1.Rows[i];
     Console.WriteLine("{0}\t{1}\t{2}\t", dr[0], dr[1], dr[2]);
 }

完整的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace test01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn dcName = new DataColumn("Name");
            DataColumn dcAge = new DataColumn("Age");
            DataColumn dcCity = new DataColumn("City");

            dt.Columns.Add(dcName);
            dt.Columns.Add(dcAge);
            dt.Columns.Add(dcCity);
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "Name" + i;
                dr[1] = "Age" + i;
                dr[2] = "City" + i;
                dt.Rows.Add(dr);
            }
            string json = JsonConvert.SerializeObject(dt);
            this.richTextBox1.Text = json;
        }
    }
}