C# 資料集轉為JSON陣列
阿新 • • 發佈:2019-02-19
public static string DataSetToJson(DataSet ds, string tblname)
{
string json = string.Empty;
try
{
if (ds.Tables.Count == 0)
throw new Exception("DataSet中Tables為0");
json = "{";
for (int i = 0; i < ds.Tables.Count; i++)
{
json += "'"+tblname+"'" + ":[";
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
json += "{";
for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
{
json += "'"+ds.Tables[i].Columns[k].ColumnName+"'" + ":'" + ds.Tables[i].Rows[j][k].ToString() + "'";
if (k != ds.Tables[i].Columns.Count - 1)
json += ",";
}
json += "}";
if (j != ds.Tables[i].Rows.Count - 1)
json += ",";
}
json += "]";
if (i != ds.Tables.Count - 1)
json += ",";
}
json += "}";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return json;
{
string json = string.Empty;
try
{
if (ds.Tables.Count == 0)
throw new Exception("DataSet中Tables為0");
json = "{";
for (int i = 0; i < ds.Tables.Count; i++)
{
json += "'"+tblname+"'" + ":[";
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
json += "{";
for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
{
json += "'"+ds.Tables[i].Columns[k].ColumnName+"'" + ":'" + ds.Tables[i].Rows[j][k].ToString() + "'";
if (k != ds.Tables[i].Columns.Count - 1)
json += ",";
}
json += "}";
if (j != ds.Tables[i].Rows.Count - 1)
json += ",";
}
json += "]";
if (i != ds.Tables.Count - 1)
json += ",";
}
json += "}";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return json;
}
依然忘了出處