首页 > 代码库 > Newtonsoft.Json 与 DataTable的相互转换
Newtonsoft.Json 与 DataTable的相互转换
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; } }}
Newtonsoft.Json 与 DataTable的相互转换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。