將DataSet轉換成json,DataSet轉換成json
/// <summary>
/// 把dataset數據轉換成json的格式
/// </summary>
/// <param name="ds">dataset數據集</param>
/// <returns>json格式的字符串</returns>
public static string GetJsonByDataset(DataSet ds)
{
if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
{
//如果查詢到的數據為空則返回標記ok:false
return "{\"ok\":false}";
}
StringBuilder sb = new StringBuilder();
sb.Append("{\"ok\":true,");
foreach (DataTable dt in ds.Tables)
{
sb.Append(string.Format("\"{0}\":[",dt.TableName));
foreach (DataRow dr in dt.Rows)
{
sb.Append("{");
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\\"").Replace("\'", "\\\'"), ObjToStr(dr[i]).Replace("\"", "\\\"").Replace("\'", "\\\'")).Replace(Convert.ToString((char)13), "
\\r\\n").Replace(Convert.ToString((char)10), "
\\r\\n");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("},");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("],");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("}");
return sb.ToString();
}
/// <summary>
/// 將object轉換成為string
/// </summary>
/// <param name="ob">obj對象</param>
/// <returns></returns>
public static string ObjToStr(object ob)
{
if (ob == null)
{
return string.Empty;
}
else
return ob.ToString();
}
ajax調用後處理
$.getJSON("page.aspx",{process:'getinfo',idx:idx},function(json){
if(json.ok==true){
$("#slGameType").val(json.Table[0].GameType);
$("#txtSelectName").val(json.Table[0].SelectName);
$("#txtmyName").val(json.Table1[0].myName);
$("#txtmyinfo").val(json.Table1[0].info);
}
});