做项目要用到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();
}