public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /**************************************************************************** * Without goingin to the depth of the functioning of this Method, i will try to give an overview * As soon as this method gets a DataTable it starts to convert it into JSON String, * it takes each row and in each row it grabs the cell name and its data. * This kind of JSON is very usefull when developer have to have Column name of the . * Values Can be Access on clien in this way. OBJ.HEAD[0].* NOTE: One negative point. by this method user will not be able to call any cell by its index. * *************************************************************************/ StringBuilder JsonString = new StringBuilder(); //Exception Handling if (dt != null && dt.Rows.Count > 0) { JsonString.Append("{ "); JsonString.Append("\"Table\":[ "); 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[i][j].ToString() + "\","); } else if (j == dt.Columns.Count - 1) { JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\""); } } /**/ /**/ /**/ /*end Of String*/ if (i == dt.Rows.Count - 1) { JsonString.Append("} "); } else { JsonString.Append("}, "); } } JsonString.Append("]}"); return JsonString.ToString(); } else { return null; } }
效果图如下:
{ "Table": [ { "id":"14","title":"长沙地铁通了","addtime":"2008-08-08"}, { "id":"15","title":"长沙","addtime":"2008-09-12"}, { "id":"17","title":"长沙","addtime":"2008-09-19"}, { "id":"21","title":"长沙","addtime":"2008-09-25"} ]}
#region dataTable转换成Json格式 ////// dataTable转换成Json格式 /// /// ///public static string ToJson(ArrayList aliJson) { StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Value\":["); for (int i = 0; i < aliJson.Count; i++) { sbuBuilder.Append("\""); sbuBuilder.Append(aliJson[i].ToString().Replace("\"", "\\\"")); sbuBuilder.Append("\","); } if (aliJson.Count > 0) { sbuBuilder.Remove(sbuBuilder.Length - 1, 1); } sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString(); strJson = strJson.Replace("\n", ""); strJson = strJson.Replace("\r", ""); return strJson;//sbuBuilder.ToString(); } public static string ToJson(DataTable dtaJson) { StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Rows\":["); for (int i = 0; i < dtaJson.Rows.Count; i++) { sbuBuilder.Append("["); for (int j = 0; j < dtaJson.Columns.Count; j++) { sbuBuilder.Append("\""); sbuBuilder.Append(dtaJson.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "")); sbuBuilder.Append("\","); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("],"); } if (dtaJson.Rows.Count > 0) { sbuBuilder.Remove(sbuBuilder.Length - 1, 1); } sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString(); strJson = strJson.Replace("\n", ""); strJson = strJson.Replace("\r", ""); return strJson;//sbuBuilder.ToString(); } #endregion dataTable转换成Json格式 #region DataSet转换成Json格式 /// /// DataSet转换成Json格式 /// /// DataSet ///public static string ToJson(DataSet dseJson) { StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Tables\":["); foreach (DataTable dtJson in dseJson.Tables) { sbuBuilder.Append(ToJson(dtJson) + ","); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString(); strJson = strJson.Replace("\n", ""); strJson = strJson.Replace("\r", ""); return strJson;//sbuBuilder.ToString(); } #endregion /// /// 带表头的 /// /// /// ///public static string ToJson(DataTable dtaJson, bool b) { StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Rows\":["); for (int i = 0; i < dtaJson.Rows.Count; i++) { sbuBuilder.Append("{ "); for (int j = 0; j < dtaJson.Columns.Count; j++) { sbuBuilder.Append("\"" + dtaJson.Columns[j].ColumnName + "\":"); sbuBuilder.Append("\""); sbuBuilder.Append(dtaJson.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "")); sbuBuilder.Append("\","); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("},"); } if (dtaJson.Rows.Count > 0) { sbuBuilder.Remove(sbuBuilder.Length - 1, 1); } sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString(); strJson = strJson.Replace("\n", ""); strJson = strJson.Replace("\r", ""); return strJson;//sbuBuilder.ToString(); } /// /// 带表头的 /// /// ///public static string ToJson(DataSet dseJson, bool b) { StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Tables\":["); foreach (DataTable dtJson in dseJson.Tables) { sbuBuilder.Append(ToJson(dtJson, true) + ","); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString(); strJson = strJson.Replace("\n", ""); strJson = strJson.Replace("\r", ""); return strJson;//sbuBuilder.ToString(); }
前台需转换:var result=eval("("+ajax(url)+")");
将DataSet(DataTable)转换成JSON格式并存储
////// 临时方法 把【字典表】生成js文件 职位等 /// public static string funTemp(string total) { DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("职位表", "dictNO,parentNO, Explainss ", "intType", total); DataTable dt = ds.Tables[0]; DataTable CurrDt = dt; StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Item\":["); for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["parentNO"] == DBNull.Value) { DataRow[] drTemp1 = dt.Select(" parentNO='" + dt.Rows[i]["dictNO"].ToString() + "'"); sbuBuilder.Append("["); for (int j = 0; j < dt.Columns.Count; j++) { sbuBuilder.Append("\""); sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "")); sbuBuilder.Append("\","); } if (dt.Rows[i]["parentNO"] == DBNull.Value) { DataTable dtTemp2 = new DataTable(); for (int j = 0; j < dt.Columns.Count; j++) { dtTemp2.Columns.Add(""); } foreach (DataRow drTemp in dt.Select(" parentNO='" + dt.Rows[i]["dictNO"].ToString() + "'")) { string[] dtAppend = new string[drTemp.ItemArray.Length]; for (int k = 0; k < drTemp.ItemArray.Length; k++) { dtAppend[k] = drTemp.ItemArray[k].ToString(); } dtTemp2.Rows.Add(dtAppend); } sbuBuilder.Append(ToJson(dtTemp2) + "}"); dtTemp2.Clear(); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("],,"); if (dt.Rows.Count > 0) { sbuBuilder.Remove(sbuBuilder.Length - 1, 1); } } } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("]}"); return sbuBuilder.ToString(); } ////// 临时方法 把字典表生成js文件 城市 /// public static string funTemp1() { DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("城市表", "intCrtyCode,intParentCrtyCode,strName,intType,strSpell ", "1", "1"); DataTable dt = ds.Tables[0]; DataTable CurrDt = dt; StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Item\":["); for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["intParentCrtyCode"].ToString() == "-1") { DataRow[] drTemp1 = dt.Select(" intParentCrtyCode='" + dt.Rows[i]["intCrtyCode"].ToString() + "'"); sbuBuilder.Append("["); for (int j = 0; j < dt.Columns.Count; j++) { sbuBuilder.Append("\""); sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "")); sbuBuilder.Append("\","); } if (dt.Rows[i]["intParentCrtyCode"].ToString() == "-1") { DataTable dtTemp2 = new DataTable(); for (int j = 0; j < dt.Columns.Count; j++) { dtTemp2.Columns.Add(""); } foreach (DataRow drTemp in dt.Select(" intParentCrtyCode='" + dt.Rows[i]["intCrtyCode"].ToString() + "'")) { string[] dtAppend = new string[drTemp.ItemArray.Length]; for (int k = 0; k < drTemp.ItemArray.Length; k++) { dtAppend[k] = drTemp.ItemArray[k].ToString(); } dtTemp2.Rows.Add(dtAppend); } sbuBuilder.Append(ToJson(dtTemp2) + "}"); dtTemp2.Clear(); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("],"); } } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("]}"); return sbuBuilder.ToString(); } ////// 临时方法 把字典表生成js文件 类别 /// public static string funTemp2() { DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("类别表", "strNumberKey,strParent,strName,strGotoUri,intOrder", "intisShow", "1"); DataTable dt = ds.Tables[0]; DataTable CurrDt = dt; StringBuilder sbuBuilder = new StringBuilder(); sbuBuilder.Append("{\"Item\":["); for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["strParent"].ToString() == "") { sbuBuilder.Append("["); for (int j = 0; j < dt.Columns.Count; j++) { sbuBuilder.Append("\""); sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "")); sbuBuilder.Append("\","); } if (dt.Rows[i]["strParent"].ToString() == "") { DataTable dtTemp2 = new DataTable(); for (int j = 0; j < dt.Columns.Count; j++) { dtTemp2.Columns.Add(""); } foreach (DataRow drTemp in dt.Select(" strParent='" + dt.Rows[i]["strNumberKey"].ToString() + "'", "intOrder desc")) { string[] dtAppend = new string[drTemp.ItemArray.Length]; for (int k = 0; k < drTemp.ItemArray.Length; k++) { dtAppend[k] = drTemp.ItemArray[k].ToString(); } dtTemp2.Rows.Add(dtAppend); } sbuBuilder.Append(ToJson(dtTemp2) + "}"); dtTemp2.Clear(); } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("],"); } } sbuBuilder.Remove(sbuBuilder.Length - 1, 1); sbuBuilder.Append("]}"); return sbuBuilder.ToString(); }////// 临时方法 生成js文件 hy /// public static void OutJsToJson_Mall() { string tempJs = ReadFile(System.Web.HttpContext.Current.Server.MapPath("~/Temp/Temp_FileMallJS.shtml")); //类别 string shopsType = hrSystem.BLL.commd.ToJosn.funTemp2(); tempJs = tempJs.Replace("{&data_shopsType&}", shopsType); WriteFile(System.Web.HttpContext.Current.Server.MapPath("~/Mall/js"), "globalMallJson.js", tempJs);//前台 // WriteFile(System.Web.HttpContext.Current.Server.MapPath("~/Sys//js/Mall"), "globalMallJson.js", tempJs);//后台 } ////// 读取 /// /// 完整路径 ///public static string ReadFile(string FileName) { using (StreamReader srFile = new StreamReader(FileName, System.Text.Encoding.UTF8)) { string strResult = srFile.ReadToEnd(); return strResult; } } /// /// 写入 /// /// 完整路劲 /// 文件名包括后缀 /// 内容 public static void WriteFile(string FilePath, string FileName, string content) { string strFilePath = FilePath + "//" + FileName; if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } StreamWriter write = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8); write.Write(content); write.Close(); } ////// 删除文件 /// public static void deleteFile(string path) { try { FileInfo file = new FileInfo(path); file.Delete(); } catch (Exception ex) { //写入日志 string msg = "删除文件【BLL.commd.deleteEntInfo】:\n 地址:" + path + "\n 时间:" + DateTime.Now.ToString("yyyyMMdd-hhmmss"); dalcomd.wLog(LogLevel.Error, msg, ex); } } //去除html标签 public static string ParseTags(string HTMLStr) { HTMLStr = HTMLStr.Replace(" ", ""); HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); HTMLStr = HTMLStr.Replace("\r\n", ""); // HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "\r\n", ""); return HTMLStr; }