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].<ColumnName>
* 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 > )
{
JsonString.Append("{ ");
JsonString.Append("\"Table\":[ ");
for (int i = ; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = ; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
}
else if (j == dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
}
}
/**/
/**/
/**/
/*end Of String*/
if (i == dt.Rows.Count - )
{
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格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(ArrayList aliJson)
{
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Value\":[");
for (int i = ; i < aliJson.Count; i++)
{
sbuBuilder.Append("\"");
sbuBuilder.Append(aliJson[i].ToString().Replace("\"", "\\\""));
sbuBuilder.Append("\",");
}
if (aliJson.Count > )
{
sbuBuilder.Remove(sbuBuilder.Length - , );
}
sbuBuilder.Append("]}");
string strJson = sbuBuilder.ToString();
strJson = strJson.Replace("\n", "<br />");
strJson = strJson.Replace("\r", "<br />");
return strJson;//sbuBuilder.ToString();
}
public static string ToJson(DataTable dtaJson)
{
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Rows\":[");
for (int i = ; i < dtaJson.Rows.Count; i++)
{
sbuBuilder.Append("[");
for (int j = ; j < dtaJson.Columns.Count; j++)
{
sbuBuilder.Append("\"");
sbuBuilder.Append(dtaJson.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "<br>"));
sbuBuilder.Append("\",");
}
sbuBuilder.Remove(sbuBuilder.Length - , );
sbuBuilder.Append("],");
}
if (dtaJson.Rows.Count > )
{
sbuBuilder.Remove(sbuBuilder.Length - , );
}
sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString();
strJson = strJson.Replace("\n", "<br />");
strJson = strJson.Replace("\r", "<br />"); return strJson;//sbuBuilder.ToString();
} #endregion dataTable转换成Json格式 #region DataSet转换成Json格式
/// <summary>
/// DataSet转换成Json格式
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
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 - , );
sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString();
strJson = strJson.Replace("\n", "<br />");
strJson = strJson.Replace("\r", "<br />");
return strJson;//sbuBuilder.ToString();
}
#endregion /// <summary>
/// 带表头的
/// </summary>
/// <param name="dtaJson"></param>
/// <param name="b"></param>
/// <returns></returns>
public static string ToJson(DataTable dtaJson, bool b)
{
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Rows\":[");
for (int i = ; i < dtaJson.Rows.Count; i++)
{
sbuBuilder.Append("{");
for (int j = ; j < dtaJson.Columns.Count; j++)
{ sbuBuilder.Append("\"" + dtaJson.Columns[j].ColumnName + "\":");
sbuBuilder.Append("\"");
sbuBuilder.Append(dtaJson.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "<br>"));
sbuBuilder.Append("\",");
}
sbuBuilder.Remove(sbuBuilder.Length - , );
sbuBuilder.Append("},");
}
if (dtaJson.Rows.Count > )
{
sbuBuilder.Remove(sbuBuilder.Length - , );
}
sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString();
strJson = strJson.Replace("\n", "<br />");
strJson = strJson.Replace("\r", "<br />"); return strJson;//sbuBuilder.ToString();
} /// <summary>
/// 带表头的
/// </summary>
/// <param name="dseJson"></param>
/// <returns></returns>
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 - , );
sbuBuilder.Append("]}"); string strJson = sbuBuilder.ToString();
strJson = strJson.Replace("\n", "<br />");
strJson = strJson.Replace("\r", "<br />");
return strJson;//sbuBuilder.ToString();
}

前台需转换:var result=eval("("+ajax(url)+")");

将DataSet(DataTable)转换成JSON格式并存储

  /// <summary>
/// 临时方法 把【字典表】生成js文件 职位等
/// </summary>
public static string funTemp(string total)
{
DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("职位表", "dictNO,parentNO, Explainss ", "intType", total);
DataTable dt = ds.Tables[];
DataTable CurrDt = dt;
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Item\":[");
for (int i = ; 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 = ; j < dt.Columns.Count; j++)
{
sbuBuilder.Append("\"");
sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "<br>"));
sbuBuilder.Append("\",");
}
if (dt.Rows[i]["parentNO"] == DBNull.Value)
{ DataTable dtTemp2 = new DataTable();
for (int j = ; 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 = ; 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 - , );
sbuBuilder.Append("],,"); if (dt.Rows.Count > )
{
sbuBuilder.Remove(sbuBuilder.Length - , );
} } }
sbuBuilder.Remove(sbuBuilder.Length - , );
sbuBuilder.Append("]}");
return sbuBuilder.ToString();
} /// <summary>
/// 临时方法 把字典表生成js文件 城市
/// </summary>
public static string funTemp1()
{
DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("城市表", "intCrtyCode,intParentCrtyCode,strName,intType,strSpell ", "", "");
DataTable dt = ds.Tables[];
DataTable CurrDt = dt;
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Item\":[");
for (int i = ; 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 = ; j < dt.Columns.Count; j++)
{
sbuBuilder.Append("\"");
sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "<br>"));
sbuBuilder.Append("\",");
}
if (dt.Rows[i]["intParentCrtyCode"].ToString() == "-1")
{ DataTable dtTemp2 = new DataTable();
for (int j = ; 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 = ; 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 - , );
sbuBuilder.Append("],");
}
}
sbuBuilder.Remove(sbuBuilder.Length - , );
sbuBuilder.Append("]}");
return sbuBuilder.ToString();
} /// <summary>
/// 临时方法 把字典表生成js文件 类别
/// </summary>
public static string funTemp2()
{
DataSet ds = hrSystem.DAL.commd.dalcomd.P_Sys_getTableCoum("类别表", "strNumberKey,strParent,strName,strGotoUri,intOrder", "intisShow", "");
DataTable dt = ds.Tables[];
DataTable CurrDt = dt;
StringBuilder sbuBuilder = new StringBuilder();
sbuBuilder.Append("{\"Item\":[");
for (int i = ; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["strParent"].ToString() == "")
{
sbuBuilder.Append("[");
for (int j = ; j < dt.Columns.Count; j++)
{
sbuBuilder.Append("\"");
sbuBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\"").Replace("\r\n", "<br>"));
sbuBuilder.Append("\",");
}
if (dt.Rows[i]["strParent"].ToString() == "")
{ DataTable dtTemp2 = new DataTable();
for (int j = ; 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 = ; 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 - , );
sbuBuilder.Append("],");
}
}
sbuBuilder.Remove(sbuBuilder.Length - , );
sbuBuilder.Append("]}");
return sbuBuilder.ToString();
} /// <summary>
/// 临时方法 生成js文件 hy
/// </summary>
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);//后台
} /// <summary>
/// 读取
/// </summary>
/// <param name="FileName">完整路径</param>
/// <returns></returns>
public static string ReadFile(string FileName)
{
using (StreamReader srFile = new StreamReader(FileName, System.Text.Encoding.UTF8))
{
string strResult = srFile.ReadToEnd();
return strResult;
}
} /// <summary>
/// 写入
/// </summary>
/// <param name="FilePath">完整路劲</param>
/// <param name="FileName">文件名包括后缀</param>
/// <param name="content">内容</param>
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();
} /// <summary>
/// 删除文件
/// </summary>
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("&nbsp;", "");
HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); HTMLStr = HTMLStr.Replace("\r\n", ""); // HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "\r\n", "");
return HTMLStr;
}

将DataSet(DataTable)转换成JSON格式(生成JS文件存储)的更多相关文章

  1. asp.net dataTable转换成Json格式

    /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...

  2. dataTable转换成Json格式

    #region dataTable转换成Json格式 /// <summary> /// /// </summary> /// <param name="dt& ...

  3. 将DataTable转换成Json格式

    方法一: 将DataTable数据拼接成json字符串,方法如下: ///<summary> /// dataTable转换成Json格式 ///</summary> ///& ...

  4. 把DataTable 转换成Json格式,适用于EasyUI 绑定DataGrid

    本文转载:http://www.cnblogs.com/liang--liang/archive/2013/02/05/2893030.html public static string DataTa ...

  5. C# DataTable 转换成JSON数据

    原文:C# DataTable 转换成JSON数据 using System; using System.Collections.Generic; using System.Data; using S ...

  6. DataTabel DataSet 对象 转换成json

    public class DataTableConvertJson    { #region dataTable转换成Json格式        /// <summary>         ...

  7. C#将datatable的某一列转换成json格式的字符串

    将datatable的某一列转换成json格式的字符串(转换完后自己在字符串前后加{}) /// <summary> ///DataTable装换 Column数据 组合成json 现在的 ...

  8. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

  9. 数据库记录转换成json格式 (2011-03-13 19:48:37) (转)

    http://blog.sina.com.cn/s/blog_621768f30100r6v7.html 数据库记录转换成json格式 (2011-03-13 19:48:37) 转载▼ 标签: 杂谈 ...

随机推荐

  1. MVC 依赖注入

    本人主要是写给我自己看的,文章没有过多的解释,只留下步骤. 目的:面向接口编程,做到低耦合,高内聚 1.利用Nuget 管理工具,安装Ninject. 2.随便新建一个接口和一个实现类,我在此项目中是 ...

  2. GDI+中发生一般性错误的解决办法(转帖)

    今天在开发.net引用程序中,需要System.Drawing.Image.Save 创建图片,debug的时候程序一切正常,可是发布到IIS后缺提示出现“GDI+中发生一般性错误”的异常.于是开始“ ...

  3. MongoDB 2.6设置访问权限、设置用户

    MongoDB已经使用很长一段时间了,基于MongoDB的数据存储也一直没有使用到权限访问(MongoDB默认设置为无权限访问限制),今天特地花了一点时间研究了一下,研究成果如下: 注:研究成果基于W ...

  4. Java设计模式-解释器模式(Interpreter)

    解释器模式是我们暂时的最后一讲,一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄. Context类是一个上下文环境类,Plus和Minus分别是用来计算的实现,代码如下: public ...

  5. SP*

    1.PS1——默认提示符 root@tcx2250-14:/etc# echo $PS1\u@\h:\w\$ \u是用户名 \h是主机名 \w是当前目录的完整路径.请注意当你在主目录下的时候,如上面所 ...

  6. 【BZOJ-1588】营业额统计 Splay

    1588: [HNOI2002]营业额统计 Time Limit: 5 Sec  Memory Limit: 162 MBSubmit: 12485  Solved: 4508[Submit][Sta ...

  7. poj 3734 矩阵快速幂+YY

    题目原意:N个方块排成一列,每个方块可涂成红.蓝.绿.黄.问红方块和绿方块都是偶数的方案的个数. sol:找规律列递推式+矩阵快速幂 设已经染完了i个方块将要染第i+1个方块. a[i]=1-i方块中 ...

  8. javaIO(三)

  9. MyEclipse------缓冲流的使用

    可以把BufferedReader和BufferedWriter称为上层流,把它们指向的字符流(Reader,Writer)称为底层流. Java采用缓存技术将上层流和底层流连接. 底层字符输入流先将 ...

  10. POI读写Excel简述之写入

    二.POI写入Excel文件(以Excel2003版为例,2007版就是根据文件扩展名xlsx将HSSFWorkbook换为XSSFWorkbook,及其Sheet.Row.Cell也相应替换) 1. ...