博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将DataSet(DataTable)转换成JSON格式(生成JS文件存储)
阅读量:5113 次
发布时间:2019-06-13

本文共 16689 字,大约阅读时间需要 55 分钟。

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; }

 

 

转载于:https://www.cnblogs.com/elves/p/3606918.html

你可能感兴趣的文章
证件照(1寸2寸)拍摄处理知识汇总
查看>>
罗马数字与阿拉伯数字转换
查看>>
Eclipse 反编译之 JadClipse
查看>>
Python入门-函数
查看>>
[HDU5727]Necklace(二分图最大匹配,枚举)
查看>>
距离公式汇总以及Python实现
查看>>
设计模式之装饰者模式
查看>>
一道不知道哪里来的容斥题
查看>>
Blender Python UV 学习
查看>>
window添加右键菜单
查看>>
入手腾龙SP AF90mm MACRO
查看>>
Window7上搭建symfony开发环境(PEAR)
查看>>
Linux内核态、用户态简介与IntelCPU特权级别--Ring0-3
查看>>
第23月第24天 git命令 .git-credentials git rm --cached git stash clear
查看>>
java SE :标准输入/输出
查看>>
一些方便系统诊断的bash函数
查看>>
jquery中ajax返回值无法传递到上层函数
查看>>
css3之transform-origin
查看>>
[转]JavaScript快速检测浏览器对CSS3特性的支持
查看>>
Master选举原理
查看>>