easyui json数据生成方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
/// <summary>
/// JsonConvert 的摘要说明
/// </summary>
public class JsonConvert
{
public JsonConvert()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary> DataTable转json格式的字符串 </summary>
/// <param name="tableSource">数据库查询结果</param>
/// <param name="fields">需要添加进来的字段名</param>
/// <returns></returns>
public string DataTableToJson(DataTable tableSource, string[] fields)
{
string jsonData = "{\"total\":" + tableSource.Rows.Count + ",\"rows\":[";
if (tableSource.Rows.Count > 0)
{
foreach (DataRow row in tableSource.Rows)
{
jsonData += "{";
for (int i = 0; i < fields.Length; i++)
jsonData += "\"" + fields[i] + "\":\"" + row[fields[i]] + "\",";
jsonData = jsonData.Substring(0, jsonData.Length - 1);
jsonData += "},";
}
jsonData = jsonData.Substring(0, jsonData.Length - 1);
jsonData += "]}";
}
else
{
jsonData += "]}";
}
return jsonData;
}
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("/"rows");
jsonBuilder.Append("/":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("/"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("/":/"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("/",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
public static string Dataset2Json(DataSet ds)
{
StringBuilder json = new StringBuilder();
foreach (DataTable dt in ds.Tables)
{
json.Append("{/"");
json.Append("total");
json.Append("/":");
json.Append(ds.Tables[0].Rows.Count);
json.Append(",");
json.Append(DataTable2Json(ds.Tables[0]));
json.Append("}");
}
return json.ToString();
}
public static string TotalJson(int totalCount, DataSet ds)
{
StringBuilder json = new StringBuilder();
foreach (DataTable dt in ds.Tables)
{
json.Append("{/"");
json.Append("total");
json.Append("/":");
json.Append(totalCount);
json.Append(",");
json.Append(DataTable2Json(ds.Tables[0]));
json.Append("}");
}
return json.ToString();
}
}