熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

DataTable轉為JSON數據格式代碼

2013-11-13 09:54:21  來源: .NET編程 

  做項目要用到DataTable轉為JSON數據在前台用ExtJs來操作所以把這個方法放上來

  代碼

   public static string GetJSON(DataTable dt)

   {

       StringBuilder sb = new StringBuilder();

       sbAppend({\totalCount\: + dtRowsCount + \data\:);

       sbAppend([);

       try

       {

           if (dtRowsCount > )

           {

               Hashtable ht = new Hashtable();

               for (int i = ; i < dtColumnsCount; i++)

               {

                   htAdd(i dtColumns[i]ColumnName);

               }

               for (int i = ; i < dtRowsCount; i++)

               {

                   sbAppend({);

                   for (int j = ; j < dtColumnsCount; j++)

                   {

                       sbAppend(stringFormat(\{}\:\{}\

                           ht[j] dtRows[i][j]ToString()));

                   }

                   sbRemove(sbToString()LastIndexOf() );

                   sbAppend(});

               }

               sbRemove(sbToString()LastIndexOf() );

               htClear();

               ht = null;

           }

       }

       catch (Exception ex)

       {

           throw new Exception(exMessage);

       }

       finally

       {

           sbAppend(]});

       }

       return sbToString();

   }


From:http://tw.wingwit.com/Article/program/net/201311/11928.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.