Convert datatable to JSON in C#

后端 未结 17 1113
猫巷女王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:39

    I have simple function to convert datatable to json string.

    I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.

    Maybe this can be useful.

     private string DataTableToJson(DataTable dt) {
      if (dt == null) {
       return "[]";
      };
      if (dt.Rows.Count < 1) {
       return "[]";
      };
    
      JArray array = new JArray();
      foreach(DataRow dr in dt.Rows) {
       JObject item = new JObject();
       foreach(DataColumn col in dt.Columns) {
        item.Add(col.ColumnName, dr[col.ColumnName]?.ToString());
       }
       array.Add(item);
      }
    
      return array.ToString(Newtonsoft.Json.Formatting.Indented);
     }
    

提交回复
热议问题