///
/// 将DataTable转换为JSON
/// 保证两个List的数量是一致的,DataTable的列数量可以多于List中值的数量
///
这段代码也可以应用到Java中,需要把对List的遍历方法由[]改为get(),DataTable替换为同种数据类即可
///
///
///
设置代表JSON中name的字符串列表(用户自定义字段名)
///
数据表中的字段名(DataTable中的列表)
///
private string DtToJSONForThree(DataTable dt, Listnamelist,
Listdatalist)
{
if (dt == null
dt.Rows.Count == 0
(namelist == null
namelist.Count == 0)
(datalist == null
datalist.Count == 0)
(namelist.Count != datalist.Count
namelist.Count > dt.Columns.Count))
{
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
sb.Append("{");
for (int j = 0; j < namelist.Count; j++)
{
sb.Append("\"" + namelist[j] + "\":\"");
sb.Append(dr[datalist[j]].ToString());
sb.Append("\",");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("},");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return Convert.ToString(sb);
}