asp.net如何将DataSet转换成josn并输出
程序员文章站
2024-02-25 10:12:16
public class jsonutil
{
public string tojson(dataset dataset)
{
string jso...
public class jsonutil { public string tojson(dataset dataset) { string jsonstring = "{"; foreach (datatable table in dataset.tables) { jsonstring += """" + table.tablename + """:" + tojson(table) + ","; } jsonstring = jsonstring.trimend(','); return jsonstring + "}"; } public string tojson(datatable dt) { stringbuilder jsonstring = new stringbuilder(); jsonstring.append("["); datarowcollection drc = dt.rows; for (int i = 0; i < drc.count; i++) { jsonstring.append("{"); for (int j = 0; j < dt.columns.count; j++) { string strkey = dt.columns[j].columnname; string strvalue = drc[i][j].tostring(); type type = dt.columns[j].datatype; jsonstring.append("""" + strkey + """:"); strvalue = string.format(strvalue, type); jsonstring.append("""" + strvalue + ""","); } jsonstring.append("},"); } jsonstring.remove(jsonstring.length - 1, 1); jsonstring.append("]"); return jsonstring.tostring(); } }
使用
jsonutil ju = new jsonutil(); response.write(ju.tojson(ds));
如果解析有问题可以把代码中的""""用"\""替换