.NET自带的json序列有时间格式问题,为了解决自己写了个json格式的序列化和反序列化
1.引入的命名空间
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; using System.Text.RegularExpressions;
2.josn的序列化
/// <summary> /// JSON序列化 /// </summary> public static string JsonSerializer<T>(this T t) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var jsonString = serializer.Serialize(t); //替换Json的Date字符串
// \\/Date\((\d+)\+?\d+\)\\/() 支持不带-的格式
string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator( m => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); } ); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); return jsonString; }
3.json的反序列化
/// <summary> /// JSON反序列化 /// </summary> public static T JsonDeserialize<T>(this string jsonString) { //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; MatchEvaluator matchEvaluator = new MatchEvaluator( m => { DateTime dt = DateTime.Parse(m.Groups[0].Value); dt = dt.ToUniversalTime(); TimeSpan ts = dt - DateTime.Parse("1970-01-01"); return string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); }); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); JavaScriptSerializer serializer = new JavaScriptSerializer(); T obj = serializer.Deserialize<T>(jsonString); return obj; }
有时候,真希望自己可以适时的穿越回去,去见见那个还是个小孩子的自己