/// <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(""'", """"'"), FieldTypeFilter.ObjToStr(dr[i]).Replace("""", """""").Replace(""'", """"'"));
}
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();
}
相应的jQuery读取json方式
/// 把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(""'", """"'"), FieldTypeFilter.ObjToStr(dr[i]).Replace("""", """""").Replace(""'", """"'"));
}
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();
}
相应的jQuery读取json方式
$.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);
}
});
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);
}
});