EasyUI的DataGrid的Json自己拼接的话非常麻烦,而且容易出错,于是写了个通用的方法!
CustomList<T>自定义类,继承于List<T>,用来处理返回的实体的总记录数和实体集合,其中属性 RecordAmout为总记录统计
JavaScriptSerializer .Net 4.0 提供的json转换方法
JavaScriptSerializer转换时间格式 "\/Date(1356019200000)\/" 默认转换为UTC格式,这样我们就需要一个小小的转换(利用正则)
sJSON = System.Text.RegularExpressions.Regex.Replace(sJSON, @"\\/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(dateTimeFormatString);
});
/// <summary>
/// CustomList转为EasyUI的DataGrid的Json格式
/// </summary>
/// <param name="cList"></param>
/// <returns></returns>
public static string CustomList2EasyUIDataGridJson<T>(CustomList<T> cList, string dateTimeFormatString = "yyyy-MM-dd HH:mm:ss")
{
System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
jsonBuilder.Append("{");
jsonBuilder.AppendFormat("\"total\":{0}, ", cList.RecordAmout);
jsonBuilder.Append("\"rows\": ");
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(cList);
sJSON = System.Text.RegularExpressions.Regex.Replace(sJSON, @"\\/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(dateTimeFormatString);
}); jsonBuilder.Append(sJSON);
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
转载请标注http://www.cnblogs.com/xushaonian/p/3246254.html
鞋子http://xiaobenxie.taobao.com
杯子http://988777.taobao.com