码迷,mamicode.com
首页 > Web开发 > 详细

Newtonsoft.Json 与 DataTable的相互转换

时间:2014-10-23 12:13:03      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   ar   for   sp   

 

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的相互转换

标签:des   style   blog   http   color   io   ar   for   sp   

原文地址:http://www.cnblogs.com/dekevin/p/4045239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!