一佳一

记录像1+1一样简洁的代码

导航

json datatable互转(真正能用的-原创)

Posted on 2013-10-11 10:57  一佳一  阅读(9896)  评论(2编辑  收藏  举报

网上有不少的转换类 可是不全 或者有错误 我现在贴一个 js 和C# 互转代码 希望能帮到需要的童鞋

首先C#转成 json


        /// <summary>
        /// DataTable转为json
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json数据</returns>
        public static string ToJson(DataTable dt)
        {
            ArrayList dic = new ArrayList();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();

                foreach (DataColumn dc in dt.Columns)
                {
                    if (dc.DataType == typeof(DateTime) && !dr[dc].ToString().Equals(""))
                        result.Add(dc.ColumnName, DateTime.Parse(dr[dc].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                    else
                        result.Add(dc.ColumnName, dr[dc].ToString());
                }
                dic.Add(result);

            }
            return ToJson(dic);
        }

 

前台接受到后生产table

然后table转json

 

 function tableToJson(tableid) {
            var txt = "[";
            var table = document.getElementById(tableid);
            var row = table.getElementsByTagName("tr");
            var col = row[0].getElementsByTagName("th");
            for (var j = 1; j < row.length; j++) {
                var r = "{";

      //这里因为我有一个操作列(修改,删除按钮) 所以-1
                for (var i = 0; i < col.length-1; i++) {
                    var tds = row[j].getElementsByTagName("td");
                    if (tds[i].getElementsByTagName("Font").length != 0) {
                        var font = tds[i].getElementsByTagName("Font")[0];
                       r += "\"" + col[i].innerHTML + "\"\:\"" + font.innerHTML + "\",";
                    }
                    else {
                        r += "\"" + col[i].innerHTML + "\"\:\"" + tds[i].innerHTML + "\",";
                    }
                  
                }
                r = r.substring(0, r.length - 1)
                r += "},";
                txt += r;
            }
            txt = txt.substring(0, txt.length - 1);
            txt += "]";
            return txt; 
        }

 

后台接收到json 转换为datatable

 

/// <summary>
        /// json转为DataTable
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string strJson)
        {
            ////取出表名 
            //Regex rg = new Regex(@"(?<={)[^:]+(?=:/[)", RegexOptions.IgnoreCase);
            //string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            ////去除表名 
            //strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            //strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据 
            Regex rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表 
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = "";
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');

                        dc.ColumnName = strCell[0].ToString().Replace("\"", "").Trim();
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容 
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("/", "").Replace("\"", "").Trim();
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }
    }

 

用了好一段时间才整理出来的,要转载的童鞋记得保留我的链接哦http://www.cnblogs.com/linyijia/p/3362916.html