转换成json字符串

转换成json字符串

将DataTable里面的行转换成json字符串方法:

         #region DataTable转为json
/// <summary>
/// DataTable转为json
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>json数据</returns>
public static string DataTableToJson(DataTable dt)
{
List<Dictionary<string, object>> list = (from DataRow dr in dt.Rows select dt.Columns.Cast<DataColumn>().ToDictionary(dc => dc.ColumnName, dc => dr[dc])).ToList();
return SerializeToJson(list);
}
#endregion #region 序列化对象为Json字符串
/// <summary>
/// 序列化对象为Json字符串
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <param name="recursionLimit">序列化对象的深度,默认为100</param>
/// <returns>Json字符串</returns>
public static string SerializeToJson(object obj, int recursionLimit = )
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serialize = new System.Web.Script.Serialization.JavaScriptSerializer();
serialize.RecursionLimit = recursionLimit;
return serialize.Serialize(obj);
}
catch { return ""; }
}
#endregion #region json包转DataTable
/// <summary>
/// json包转DataTable
/// </summary>
/// <param name="jsons"></param>
/// <returns></returns>
public static DataTable JsonToDataTable(string jsons)
{
DataTable dt = new DataTable();
try
{
System.Web.Script.Serialization.JavaScriptSerializer serialize = new System.Web.Script.Serialization.JavaScriptSerializer();
serialize.MaxJsonLength = Int32.MaxValue;
ArrayList list = serialize.Deserialize<ArrayList>(jsons);
if (list.Count > )
{
foreach (Dictionary<string, object> item in list)
{
if (item.Keys.Count == )//无值返回空
{
return dt;
}
if (dt.Columns.Count == )//初始Columns
{
foreach (string current in item.Keys)
{
dt.Columns.Add(current, item[current].GetType());
}
}
DataRow dr = dt.NewRow();
foreach (string current in item.Keys)
{
dr[current] = item[current];
}
dt.Rows.Add(dr);
}
}
}
catch
{
return dt;
}
return dt;
}
#endregion
04-18 09:07