DataTabe转JSON
代码附上:
public static string DataTableToJSON(DataTable dt, string dtName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
jw.WritePropertyName(dtName);
jw.WriteStartArray();
foreach (DataRow dr in dt.Rows)
{
jw.WriteStartObject();
foreach (DataColumn dc in dt.Columns)
{
jw.WritePropertyName(dc.ColumnName);
ser.Serialize(jw, dr[dc].ToString());
}
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
sw.Close();
jw.Close();
}
return sb.ToString();
}
dt:需要转换的DataTable的数据源
dtName:附加JSON名。(YY:区分JSON传送的数据用的)
2:在Jquery使用这JSON就有些麻烦
需要用2个for循环调出里面的数据
for (var i in json) {
for (var j in json[i]) {
lew += '<li><a href=News.aspx?newid=' + json[i][j].newsid + '>';
lew += json[i][j].title + '</li>';
}
}