且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.NET DataTable转化为json格式

更新时间:2022-05-19 18:46:44

标准的json用“分隔,不用' 

public static string DataSetToJson(DataTable dt)

   {
       string json = string.Empty;
       try
       {
           if (dt==null||dt.Rows.Count == 0)
           {
               return "";
           }
           json = "{";
           json += "'table" + 1 + "':[";
           for (int i = 0; i < dt.Rows.Count; i++)
           {
               json += "{";
               for (int j = 0; j < dt.Columns.Count; j++)
               {
                   json += "'" + dt.Columns[j].ColumnName + "':'" + dt.Rows[i][j].ToString() + "'";
                   if (j != dt.Columns.Count - 1)
                   {
                       json += ",";
                   }
               }
               json += "}";
               if (i != dt.Rows.Count - 1)
               {
                   json += ",";
               }
           }
           json += "]";
           json += "}";
       }
       catch (Exception ex)
       {

           throw new Exception(ex.Message);
       }
       return json;
   }