DataTable转换成Json
时间:2011-05-24 来源:#阿志#
using Newtonsoft.Json; //这个google 下。
public static string DtToSON(DataTable dt)
{
StringBuilder jsonSB = new StringBuilder();
StringWriter sw = new StringWriter(jsonSB);
JsonWriter jWriter = new JsonWriter(sw);
jWriter.Formatting = Newtonsoft.Json.Formatting.None;
jWriter.WriteStartObject();
int cnt = 0;
if (dt != null)
{
cnt = dt.Rows.Count;
}
jWriter.WritePropertyName(dt.TableName);
jWriter.WriteStartArray();
for (int i = 0; i < dt.Rows.Count; i++)
{
jWriter.WriteStartObject();
for (int j = 0; j < dt.Columns.Count; j++)
{
jWriter.WritePropertyName(dt.Columns[j].ColumnName);
jWriter.WriteValue(dt.Rows[i][j].ToString());
}
jWriter.WriteEndObject();
}
jWriter.WriteEndArray();
jWriter.WriteEndObject();
return jsonSB.ToString();
}