c#常用的Datable转换为json,以及json转换为DataTable操作方法

来源:互联网 发布:广电网络的营业员 编辑:程序博客网 时间:2024/06/05 04:19
/*==============================================================================
*
* Filename: DatatableToJson.cs
* Description: 主要包含两个方法:
   1. 获取的DataTable 对象 转换为Json 字符串
   2. Json 字符串 转换为 DataTable数据集合
* Version: 1.0
* Created: 2012.08.23
* Author: liangjw
* E-mail : liangjw0504@163.com
* Q   Q   : 592568532
* Company: Copyright (C) Create Family Wealth Power By Peter
*
==============================================================================*/
 * 备注信息: 上传部分自己总结的常用方法的封装,有不足和不完美之处,希望大家指出来,愿意一起
 * 主要研究erp,cms,crm,b2b,oa等系统和网站的开发,欢迎有共同追求和学的IT人员一起学习和交流。
 * 学习和讨论有关asp.net  mvc ,Ajax ,jquery ,html/css, xml ,sqlserver ,wpf,IIS以及服务器的搭建和安全性相关技术的交流和学习。
标签: <无>

代码片段(1)[全屏查看所有代码]

1. [代码][C#]Datatable和json互相转换操作     跳至 [1] [全屏预览]

view source
print?
001#region  DataTable 转换为Json字符串实例方法
002/// <summary>
003/// GetClassTypeJosn 的摘要说明
004/// </summary>
005public class GetClassTypeJosn : IHttpHandler
006{
007    /// <summary>
008    /// 文件名:DataTable 和Json 字符串互转
009    /// 版权所有:Copyright (C) Create Family Wealth liangjw
010    /// 创建标示:2013-08-03
011    /// </summary>
012    //用法说明实例
013     public void ProcessRequest(HttpContext context)
014    {
015        context.Response.ContentType = "application/json";
016        context.Response.Charset = "utf-8";
017        HttpRequest req = context.Request;
018        string method = req["method"].ToStr().ToLower();
019 
020 
021       //获取合同明细列表  DataTable 转换为Json字符串
022        if (method == "txtdate")
023        {
024            string json = "";
025            BO.MakeContractMx bll = new MakeContractMx();
026            DataSet ds = bll.GetDataTable();
027            if (ds.Tables.Count > 0)
028            {
029                json =ToJson(ds.Tables[0]);
030            }
031            context.Response.Write(json);
032            return;
033        }
034 
035    }
036 
037   public bool IsReusable
038    {
039        get
040        {
041            return false;
042        }
043    }
044}
045 
046   #endregion
047 
048    #region Json字符串转换为DataTable 实例方法
049 
050    public DataTable JsonToDataTable(json)
051    {
052       DataTable  dt= ToDataTable(json);
053         return dt;
054    }
055     
056   #endregion
057 
058    #region DataTable 转换为Json 字符串
059    /// <summary>
060    /// DataTable 对象 转换为Json 字符串
061    /// </summary>
062    /// <param name="dt"></param>
063    /// <returns></returns>
064    public static string ToJson(this DataTable dt)
065    {
066        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
067        javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
068        ArrayList arrayList = new ArrayList();
069        foreach (DataRow dataRow in dt.Rows)
070        {
071            Dictionary<stringobject> dictionary = new Dictionary<stringobject>(); //实例化一个参数集合
072            foreach (DataColumn dataColumn in dt.Columns)
073            {
074                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
075            }
076            arrayList.Add(dictionary); //ArrayList集合中添加键值
077        }
078 
079        return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
080    }
081    #endregion
082 
083    #region Json 字符串 转换为 DataTable数据集合
084    /// <summary>
085    /// Json 字符串 转换为 DataTable数据集合
086    /// </summary>
087    /// <param name="json"></param>
088    /// <returns></returns>
089    public static DataTable ToDataTable(this string json)
090    {
091        DataTable dataTable = new DataTable();  //实例化
092        DataTable result;
093        try
094        {
095            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
096            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
097            ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
098            if (arrayList.Count > 0)
099            {
100                foreach (Dictionary<stringobject> dictionary in arrayList)
101                {
102                    if (dictionary.Keys.Count<string>() == 0)
103                    {
104                        result = dataTable;
105                        return result;
106                    }
107                    if (dataTable.Columns.Count == 0)
108                    {
109                        foreach (string current in dictionary.Keys)
110                        {
111                            dataTable.Columns.Add(current, dictionary[current].GetType());
112                        }
113                    }
114                    DataRow dataRow = dataTable.NewRow();
115                    foreach (string current in dictionary.Keys)
116                    {
117                        dataRow[current] = dictionary[current];
118                    }
119 
120                    dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
121                }
122            }
123        }
124        catch
125        {
126        }
127        result = dataTable;
128        return result;
129    }
130    #endregion
131 
132    #region 转换为string字符串类型
133    /// <summary>
134    ///  转换为string字符串类型
135    /// </summary>
136    /// <param name="s">获取需要转换的值</param>
137    /// <param name="format">需要格式化的位数</param>
138    /// <returns>返回一个新的字符串</returns>
139    public static string ToStr(this object s, string format = "")
140    {
141        string result = "";
142        try
143        {
144            if (format == "")
145            {
146                result = s.ToString();
147            }
148            else
149            {
150                result = string.Format("{0:" + format + "}", s);
151            }
152        }
153        catch
154        {
155        }
156        return result;
157    }
158   #endregion
/*==============================================================================
*
* Filename: DatatableToJson.cs
* Description: 主要包含两个方法:
   1. 获取的DataTable 对象 转换为Json 字符串
   2. Json 字符串 转换为 DataTable数据集合
* Version: 1.0
* Created: 2012.08.23
* Author: liangjw
* E-mail : liangjw0504@163.com
* Q   Q   : 592568532
* Company: Copyright (C) Create Family Wealth Power By Peter
*
==============================================================================*/
 * 备注信息: 上传部分自己总结的常用方法的封装,有不足和不完美之处,希望大家指出来,愿意一起
 * 主要研究erp,cms,crm,b2b,oa等系统和网站的开发,欢迎有共同追求和学的IT人员一起学习和交流。
 * 学习和讨论有关asp.net  mvc ,Ajax ,jquery ,html/css, xml ,sqlserver ,wpf,IIS以及服务器的搭建和安全性相关技术的交流和学习。
标签: <无>

代码片段(1)[全屏查看所有代码]

1. [代码][C#]Datatable和json互相转换操作     跳至 [1] [全屏预览]

view source
print?
001#region  DataTable 转换为Json字符串实例方法
002/// <summary>
003/// GetClassTypeJosn 的摘要说明
004/// </summary>
005public class GetClassTypeJosn : IHttpHandler
006{
007    /// <summary>
008    /// 文件名:DataTable 和Json 字符串互转
009    /// 版权所有:Copyright (C) Create Family Wealth liangjw
010    /// 创建标示:2013-08-03
011    /// </summary>
012    //用法说明实例
013     public void ProcessRequest(HttpContext context)
014    {
015        context.Response.ContentType = "application/json";
016        context.Response.Charset = "utf-8";
017        HttpRequest req = context.Request;
018        string method = req["method"].ToStr().ToLower();
019 
020 
021       //获取合同明细列表  DataTable 转换为Json字符串
022        if (method == "txtdate")
023        {
024            string json = "";
025            BO.MakeContractMx bll = new MakeContractMx();
026            DataSet ds = bll.GetDataTable();
027            if (ds.Tables.Count > 0)
028            {
029                json =ToJson(ds.Tables[0]);
030            }
031            context.Response.Write(json);
032            return;
033        }
034 
035    }
036 
037   public bool IsReusable
038    {
039        get
040        {
041            return false;
042        }
043    }
044}
045 
046   #endregion
047 
048    #region Json字符串转换为DataTable 实例方法
049 
050    public DataTable JsonToDataTable(json)
051    {
052       DataTable  dt= ToDataTable(json);
053         return dt;
054    }
055     
056   #endregion
057 
058    #region DataTable 转换为Json 字符串
059    /// <summary>
060    /// DataTable 对象 转换为Json 字符串
061    /// </summary>
062    /// <param name="dt"></param>
063    /// <returns></returns>
064    public static string ToJson(this DataTable dt)
065    {
066        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
067        javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
068        ArrayList arrayList = new ArrayList();
069        foreach (DataRow dataRow in dt.Rows)
070        {
071            Dictionary<stringobject> dictionary = new Dictionary<stringobject>(); //实例化一个参数集合
072            foreach (DataColumn dataColumn in dt.Columns)
073            {
074                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
075            }
076            arrayList.Add(dictionary); //ArrayList集合中添加键值
077        }
078 
079        return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
080    }
081    #endregion
082 
083    #region Json 字符串 转换为 DataTable数据集合
084    /// <summary>
085    /// Json 字符串 转换为 DataTable数据集合
086    /// </summary>
087    /// <param name="json"></param>
088    /// <returns></returns>
089    public static DataTable ToDataTable(this string json)
090    {
091        DataTable dataTable = new DataTable();  //实例化
092        DataTable result;
093        try
094        {
095            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
096            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
097            ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
098            if (arrayList.Count > 0)
099            {
100                foreach (Dictionary<stringobject> dictionary in arrayList)
101                {
102                    if (dictionary.Keys.Count<string>() == 0)
103                    {
104                        result = dataTable;
105                        return result;
106                    }
107                    if (dataTable.Columns.Count == 0)
108                    {
109                        foreach (string current in dictionary.Keys)
110                        {
111                            dataTable.Columns.Add(current, dictionary[current].GetType());
112                        }
113                    }
114                    DataRow dataRow = dataTable.NewRow();
115                    foreach (string current in dictionary.Keys)
116                    {
117                        dataRow[current] = dictionary[current];
118                    }
119 
120                    dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
121                }
122            }
123        }
124        catch
125        {
126        }
127        result = dataTable;
128        return result;
129    }
130    #endregion
131 
132    #region 转换为string字符串类型
133    /// <summary>
134    ///  转换为string字符串类型
135    /// </summary>
136    /// <param name="s">获取需要转换的值</param>
137    /// <param name="format">需要格式化的位数</param>
138    /// <returns>返回一个新的字符串</returns>
139    public static string ToStr(this object s, string format = "")
140    {
141        string result = "";
142        try
143        {
144            if (format == "")
145            {
146                result = s.ToString();
147            }
148            else
149            {
150                result = string.Format("{0:" + format + "}", s);
151            }
152        }
153        catch
154        {
155        }
156        return result;
157    }
158   #endregion
1 0