Convert DataTable type to List<T> collection & Json type

  • ASP.Net WebForm applications using 一般处理程序 .ashxAjax to the data Jsonwhen the type of display in the foreground
  • Since the DataTabletype can not be directly converted into a Jsonformat, by the DataTabletype first converted into a List<T>set, then the List<T>set is converted into Jsonthe format

Conversion process

  • The DataTableconversion type into List<T>the collection
public static List<Student> GetStuInfo()
{
    
    
    string sql = @"select ID,Name from StudentInfo";
    DataTable dt = Helper.DBHelper.GetDataTable(sql, null);
    
    //实例化一个 Student 的 List<T>集合
    List<Student> list = new List<Student>();
    foreach (DataRow item in dt.Rows)
    {
    
    
    	// 实例化一个 Student 类的对象
        Student info = new Student
        {
    
    
            ID = Convert.ToInt32(item["ID"]),
            Name = item["Name"].ToString(),
        };
        list.Add(info);
    }
    return list;
}
  • The List<T>aggregate data set into a sequence Jsonformat
//引入命名空间(用于 Json 序列化)
using System.Web.Script.Serialization;

public static void SelStuInfo(HttpContext context)
{
    
    
	// 获取 上述方法返回的list集合数据集
    var stuinfo = GetStuInfo();
    // 实例化一个  jss 对象 用于 将list集合数据 序列化为 Json 格式
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string json = jss.Serialize(stuinfo);
    // 输出 序列化 后的 Json 数据集
    context.Response.Write(json);
}
  • At this point the end of conversion, data sets will be Jsonformat show in the foreground

Guess you like

Origin blog.csdn.net/qq_43562262/article/details/109234777
Recommended