首先我们看看 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互转的功能。