C# DataTable转json 时间格式化
2021-05-30 01:12
标签:null sof json == for regular 格式 code return 1.NewTonSoft.json 2.net frework 版本4.5以上 C# DataTable转json 时间格式化 标签:null sof json == for regular 格式 code return 原文地址:https://www.cnblogs.com/SoftWareIe/p/11067675.html public static string DataTableToJson(DataTable dt)
{
if (dt == null && dt.Rows.Count 0)
{
return "";
}
else
{
IsoDateTimeConverter convert = new IsoDateTimeConverter();
convert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
return JsonConvert.SerializeObject(dt, Formatting.None, convert);
}
}
public static string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
System.Collections.ArrayList dic = new System.Collections.ArrayList();
foreach (DataRow dr in dtb.Rows)
{
System.Collections.Generic.Dictionarystring, object> drow = new System.Collections.Generic.Dictionarystring, object>();
foreach (DataColumn dc in dtb.Columns)
{
drow.Add(dc.ColumnName, dr[dc.ColumnName]);
}
dic.Add(drow);
}
//序列化
string jsonStr = jss.Serialize(dic);
jsonStr = System.Text.RegularExpressions.Regex.Replace(jsonStr, @"\\/Date\((\d+)\)\\/", match =>
{
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
dt = dt.ToLocalTime();
return dt.ToString("yyyy-MM-dd HH:mm:ss");
});
return jsonStr;
}