DataTable转换为JSON数组

时间:2024-01-10 14:33:33

最后的格式为:[{},{},...]

StringBuilder DataTableToJSON(DataTable dt)
{
  string columnName;
  StringBuilder builder = new StringBuilder();
  if (dt != null && dt.Rows.Count >= 1)
  {
    builder.Append("[");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
      builder.Append("{");
      for (int j = 0; j < dt.Columns.Count; j++)
      {
        columnName = dt.Columns[j].ColumnName;
        builder.Append("\"" + columnName + "\":");
        builder.Append("\"" + dt.Rows[i][columnName] + "\",");
      }
      builder.Append("},");
    }
    builder.Append("]");
    builder = builder.Replace(",}", "}").Replace(",]", "]"); //去掉最后面多余的逗号
  }
  return builder;
}

 Dictionary<string, object> ToDictionary(DataTable dt)
 {
     Dictionary<string, object> dic = new Dictionary<string, object>();
     )
     {
         foreach (DataColumn dc in dt.Columns)
         {
             dic.Add(dc.ColumnName, string.Empty);
         }
     }
     else
     {
         DataRow dr = dt.Rows[];
         foreach (DataColumn dc in dt.Columns)
         {
             dic.Add(dc.ColumnName, dr[dc.ColumnName]);
         }
     }
     return dic;
 }

一条数据的DataTable转字典集合