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(" ", "");
HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); HTMLStr = HTMLStr.Replace("\r\n", ""); // HTMLStr = System.Text.RegularExpressions.Regex.Replace(HTMLStr, "\r\n", "");
return HTMLStr;
}