做項目要用到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