你的位置:首页 > ASP.net教程

[ASP.net教程]DataTable转换为JSON


 

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

StringBuilder DataTableToJSON(DataTable dt)
{
  string columnName;
  StringBuilder builder = new StringBuilder();
  if (dt != null)
  {
    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;
}