Convert datatable to JSON in C#

后端 未结 17 1321
猫巷女王i
猫巷女王i 2020-11-22 11:53
  1. I want to get records from database into a DataTable.
  2. Then convert the DataTable into a JSON object.
  3. Return the JSON ob
17条回答
  •  孤城傲影
    2020-11-22 12:54

    try this (ExtensionMethods):

    public static string ToJson(this DataTable dt)
    {
        List> lst = new List>();
        Dictionary item;
        foreach (DataRow row in dt.Rows)
        {
                item = new Dictionary();
                    foreach (DataColumn col in dt.Columns)
                    {
                        item.Add(col.ColumnName, (Convert.IsDBNull(row[col]) ? null : row[col]));       
            }
            lst.Add(item);
        }
            return Newtonsoft.Json.JsonConvert.SerializeObject(lst);
    }
    

    and use:

    DataTable dt = new DataTable();
    .
    .
    .
    var json = dt.ToJson();
    

提交回复
热议问题