C#实现将Dataset数据转换为Json数据。
代码如下:
/// <summary>
/// DataSet对象转换为Josn
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
public static string GetJsonString(DataSet ds)
{
string json = string.Empty;
IList<Hashtable> mList = new List<Hashtable>();
try
{
foreach (DataRow row in ds.Tables[0].Rows)
{
Hashtable ht = new Hashtable();
foreach (DataColumn col in ds.Tables[0].Columns)
{
ht.Add(col.ColumnName, row[col.ColumnName]);
}
mList.Add(ht);
}
json = javascriptConvert.SerializeObject(mList);
}
catch (Exception ex)
{
string error = ex.Message;
}
return json;
}
public static string CreateJsonByDataTable(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
if (dt != null && dt.Rows.Count > 0)
{
jsonString.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
jsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + "",");
}
else if (j == dt.Columns.Count - 1)
{
jsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + """);
}
}
if (i == dt.Rows.Count - 1)
{
jsonString.Append("}");
}
else
{ //www.jb200.com
jsonString.Append("},");
}
}
jsonString.Append("]");
return jsonString.ToString();
}
else
{
return string.Empty;
}
}