#region 将datatable格式转换成 json格式
public static string DataSetToJson(DataTable dt)
{
string json = string.Empty;
try
{
if (dt == null || dt.Rows.Count == 0)
{
return "";
}
json = "{";
json += "‘table" + 1 + "‘:[";
for (int i = 0; i < dt.Rows.Count; i++)
{
json += "{";
for (int j = 0; j < dt.Columns.Count; j++)
{
json += "‘" + dt.Columns[j].ColumnName + "‘:‘" + dt.Rows[i][j].ToString() + "‘";
if (j != dt.Columns.Count - 1)
{
json += ",";
}
}
json += "}";
if (i != dt.Rows.Count - 1)
{
json += ",";
}
}
json += "]";
json += "}";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return json;
}
#endregion
#region 将json格式解析成datatable格式
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("]"));
//获取数据
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 = strName;
foreach (string str in strRows)
{
DataColumn dc = new DataColumn();
string[] strCell = str.Split(‘:‘);
dc.ColumnName = strCell[0].ToString().Trim().Replace("‘", "");
// row[dc.ColumnName] = strCell[1].ToString();
tb.Columns.Add(dc);
// t .Columns[strCell[0].ToString()].te
}
tb.AcceptChanges();
}
DataRow row = tb.NewRow();
foreach (var item in strRows)
{
string[] strCell1 = item.Split(‘:‘);
string lie = strCell1[0].ToString().Trim().Replace("‘", "");
string zhi = strCell1[1].ToString().Trim().Replace("‘", "");
// row[strCell1[0].ToString()] = strCell1[1].ToString();
row[lie] = zhi;
}
tb.Rows.Add(row);
// t .Columns[strCell[0].ToString()].te
}
tb.AcceptChanges();
return tb;
}
#endregion
原文地址:http://smileface.blog.51cto.com/5740492/1714712