第一个发送到前台要eval一下.转换成JS的数组
第二个转换成真正的JSON数据
/// <summary>
/// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。
/// </summary>
/// <param name="source">需要转换的表。</param>
/// <returns></returns>
public static string DataTableToJson(DataTable source)
{
if (source.Rows.Count == 0)
return "";
StringBuilder sb = new StringBuilder("[");
foreach (DataRow row in source.Rows)
{
sb.Append("[");
for (int i = 0; i < source.Columns.Count; i++)
{
sb.Append('"' + row.ToString() + "\",");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("],");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// 反回JSON数据到前台
/// </summary>
/// <param name="dt">数据表</param>
/// <returns>JSON字符串</returns>
public string CreateJsonParameters(DataTable dt)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append("{ ");
JsonString.Append("\"TableInfo\":[ ");
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[j].ToString() + "\",");
}
else if (j == dt.Columns.Count - 1)
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[j].ToString() + "\"");
}
}
/**/
/*end Of String*/
if (i == dt.Rows.Count - 1)
{
JsonString.Append("} ");
}
else
{
JsonString.Append("}, ");
}
}
JsonString.Append("]}");
return JsonString.ToString();
}
else
{
return null;
}
}
/**//// <summary>
///JsonHelp 的摘要说明
/// </summary> public static class JsonHelp
{
/**//// <summary>
/// 返回对象序列化
/// </summary>
/// <param name="obj">源对象</param>
/// <returns>json数据</returns>
public static string ToJson(this object obj)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
return serialize.Serialize(obj);
}
/**//// <summary>
/// 控制深度
/// </summary>
/// <param name="obj">源对象</param>
/// <param name="recursionDepth">深度</param>
/// <returns>json数据</returns>
public static string ToJson(this object obj, int recursionDepth)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.RecursionLimit = recursionDepth;
return serialize.Serialize(obj);
}
/**//// <summary>
/// DataTable转为json
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>json数据</returns>
public static string ToJson(DataTable dt)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
int index = 0;
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName, dr[dc].ToString());
}
dic.Add(index.ToString(), result);
index++;
}
return dic.ToJson();
}
}
本作品采用知识共享署名-非
商业性使用-相同方式共享 3.0 Unported许可
协议
欢迎转载,但必须保留文章的署名刘巨(艾梦尔)
并保留此链接:http://liuju150.cnb
logs.com/
如有疑问请发邮件:liuju150@vip.qq.com