C#实现DataSet数据转换为Json的代码
本文导语: C#实现将Dataset数据转换为Json数据。 代码如下: 代码示例: /// /// DataSet对象转换为Josn /// /// /// public static string GetJsonString(DataSet ds) { string json = string.Empty; IList mList = new List(); try { foreach (DataRow ...
C#实现将Dataset数据转换为Json数据。
代码如下:
///
/// DataSet对象转换为Josn
///
///
///
public static string GetJsonString(DataSet ds)
{
string json = string.Empty;
IList mList = new List();
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.
jsonString.Append("},");
}
}
jsonString.Append("]");
return jsonString.ToString();
}
else
{
return string.Empty;
}
}