json与DataTable相互转换

首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的:

           DataTable table = new DataTable();
            table.Columns.Add("id");
            table.Columns.Add("name");
            table.Columns.Add("url");
            table.Rows.Add("1", "zhengdjin", "http://blog.csdn.net/zhengdjin");
            table.Rows.Add("2", "生活信息网", "http://www.naoqiu.com");

           //Newtonsoft.Json api:
            //序列化
            string api_s= Newtonsoft.Json.JsonConvert.SerializeObject(table);
            Console.WriteLine(api_s);
            //反序列化
            DataTable api_Table = Newtonsoft.Json.JsonConvert.DeserializeObject(api_s, typeof(DataTable)) as DataTable;
            Console.ReadLine();

实现的方式相当简单,微软都帮我处理掉那些繁杂的操作,那我们来还原将DataTable转换为Json格式的情景:

我为了做更多的扩展,首先创建一个json基类代码如下:

  /// <summary>
    /// json基类
    /// </summary>
    public abstract class IJson<T>
    {
        /// <summary>
        /// 行信息区域块表示方式
        /// </summary>
        private string _rowInfo = "{}";
        /// <summary>
        /// 行分割字符
        /// </summary>
        private char _rowSp = ‘,‘;
        /// <summary>
        /// 列分割字符
        /// </summary>
        private char _columnSp = ‘,‘;

        /// <summary>
        /// 行分割字符
        /// </summary>
        public char RowSplit {
            get { return _rowSp; }
            set { _rowSp = value; }
        }
        /// <summary>
        /// 列分割字符
        /// </summary>
        public char ColumnSplit {
            get { return _columnSp; }
            set { _columnSp = value; }
        }
        /// <summary>
        /// 行信息区域块表示方式
        /// </summary>
        public string RowInfo
        {
            get { return _rowInfo; }
            set { _rowInfo = value; }
        }

        /// <summary>
        /// 默认json转化参数格式
        /// </summary>
        public IJson() : this(‘,‘, ‘,‘, "{}") { }

        public IJson(char rSplit, char cSplit, string rInfo)
        {
            this._rowSp=rSplit;
            this._columnSp = cSplit;
            this._rowInfo = rInfo;
        }

        /// <summary>
        /// 转化为json对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">参数</param>
        /// <returns></returns>
        public abstract string toJson<T>(T t);

        /// <summary>
        /// jsaon转化对象
        /// </summary>
        /// <param name="json">jsaon字符</param>
        /// <returns>对象</returns>
        public abstract T toObject(string json);
    }

接下来定义一个JsontoDataTable 继承json基类,然后实现 toJson<T>(T t) 将dataTable转换为json

     /// <summary>
        /// dataTable转化为json对象
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="t">参数</param>
        /// <returns></returns>
        public override string toJson<T>(T t)
        {
            DataTable table = t as DataTable;
            if (table == null) return "";
            if (RowInfo.Length != 2) throw new NotImplementedException("行信息区域块表示方式格式不正确");
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append(table.TableName+":[");
            string head = "";
            int i = 0;
            foreach (DataColumn dc in table.Columns){
                head += dc.ColumnName + ":" + (dc.DataType == typeof(int) || dc.DataType == typeof(decimal) ?
                    "{" + i++.ToString() + "}" : "\"{" + i++.ToString() + "}\"") + ColumnSplit.ToString();
            }
            head = head.TrimEnd(ColumnSplit);
            foreach (DataRow dr in table.Rows){
                jsonBuilder.Append(RowInfo[0].ToString());
                jsonBuilder.AppendFormat(head, dr.ItemArray.ToArraybySpecial());
                jsonBuilder.Append(RowInfo[1].ToString() + RowSplit.ToString());
            }
            return jsonBuilder.ToString().Trim(RowSplit) + "]";
        }

到这里已经完成了DataTable转换为json ,现在还差个将json转化为DataTable,这个方法相对难度比DataTable转换json稍微。实现这个方法过程中我们得使用正则表达式来获取数据(可参考asp.net如何加快页面加载(三)——浅谈正则应用)。

     /// <summary>
        /// json转化为DataTable
        /// </summary>
        /// <param name="json">json变量</param>
        /// <returns>DataTable</returns>
        public override DataTable toObject(string json)
        {
            string pattern_row = @"(" + RowInfo[0] + "(.|\n)*?(" + RowInfo[1] + RowSplit +
                @")|" + RowInfo[0] + "(.|\n)*?(" + RowInfo[1] + @"\]))";
            //获取行记录
            MatchCollection matches = Regex.Matches(json, pattern_row);
            if (matches.Count == 0) return null;
            //获取列名
            MatchCollection matches_columns = Regex.Matches(matches[0].Value, "(?<=[" + RowInfo[0].ToString() + ColumnSplit.ToString() + @"])[^\:]+");
            DataTable table = new DataTable();
            //绑定列名
            foreach (Match m in matches_columns) {
                table.Columns.Add(m.Value);
            }
            //绑定数据
            DataRow dr;
            string value;
            foreach (Match m in matches) {
                dr = table.NewRow();
                foreach (Match mc in matches_columns) {
                    value = Regex.Match(m.Value, "(?<=[" + RowInfo[0].ToString() + ColumnSplit.ToString() + "]+" + mc.Value + @"\:)[\d\.]+").Value;
                    if (value == "") {
                        value = Regex.Match(m.Value, "(?<=[" + RowInfo[0].ToString() + ColumnSplit.ToString() + "]+" +
                            mc.Value + @"\:\"")(.|\n)*?\""[" + ColumnSplit.ToString() + RowInfo[1].ToString() + "]").Value;
                    }
                    dr[mc.Value] = Regex.Replace(value, "\"[" + ColumnSplit.ToString() + RowInfo[1].ToString() + "]", "").toDesSpecial();
                }
                table.Rows.Add(dr);
            }
            return table;
        }

到这里完成了json 与DataTable互转的功能。

时间: 2024-10-13 04:56:29

json与DataTable相互转换的相关文章

#region Json转DataTable

#region  Json转DataTable        private DataTable Json2Dtb(string json)        {            JavaScriptSerializer jss = new JavaScriptSerializer();            ArrayList dic = jss.Deserialize<ArrayList>(json);            DataTable dtb = new DataTable()

php中 xml json 数组 之间相互转换

php中 xml json  数组 之间相互转换 1 数组转json $result = array( 'status' =>$status, 'message'=>$message, 'data'=>$data, ); json_encode($result);

字典和JSON格式字符串相互转换

在iOS开发中,和服务器交互中,经常用到字典和JSON格式字符串相互转换. 1.JSON格式字符串转字典 + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDi

json转datatable(正则表达式的方法)

/// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> private DataTable JsonToDataTable(string strJson) { //转换json格式 strJson = strJson.Replace(&qu

C# 中 Json 和 DataTable的转换方法

public static DataTable JsonToDataTable(string json) { DataTable dt = null; dt = new DataTable();//实例化 JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arr

c# 将json转换为DataTable

/// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> public static DataTable JsonToDataTable(string strJson) { //转换json格式 strJson = strJson.Repla

C#实现将json转换为DataTable的方法

本文实例讲述了C#实现将json转换为DataTable的方法.分享给大家供大家参考.具体实现方法如下: 代码如下: #region 将json转换为DataTable /// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> private

DataTable转Json Json转DataTable

DataTable转Json Json转DataTable /// <summary>        /// DataTable转Json        /// </summary>        /// <param name="dtb"></param>        /// <returns></returns>        #region DataTable转Json    private string 

PCB MS SQL 存储过程(CLR) 实现Json转DataTable表的方法

一.准备需转为DataTable的json字符串 原json字符串数据 [{"TechName":"ECN","TechNo":"EC_01","id":"1"},{"TechName":"流程指示","TechNo":"PI_01","id":"2"},{"