public class JsonHelper { ////// 将Model转换为Json字符串 /// ////// /// public static string GetJson (T obj) { try { DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { json.WriteObject(ms, obj); string strJson = Encoding.UTF8.GetString(ms.ToArray()); string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator me = new MatchEvaluator(ConvertJsonDateToDateString); Regex rg = new Regex(p); strJson = rg.Replace(strJson, me); return strJson; } } catch (Exception ex) { } return string.Empty; } /// /// 将Json字符串转换为Model /// ////// /// public static T ParseJson (string strJson) { try { string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}[a-z,A-Z]"; MatchEvaluator me = new MatchEvaluator(ConvertDateTimeToJsonDate); Regex rg = new Regex(p); strJson = rg.Replace(strJson, me); p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; me = new MatchEvaluator(ConvertDateTimeToJsonDate); rg = new Regex(p); strJson = rg.Replace(strJson, me); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); T obj = (T)serializer.ReadObject(ms); return obj; } } catch (Exception ex) { } return default(T); } /// /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 /// /// ///private static string ConvertJsonDateToDateString(Match m) { string result = string.Empty; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); result = dt.ToString("yyyy-MM-dd HH:mm:ss"); return result; } /// /// 将时间字符串转化成json时间 /// /// ///private static string ConvertDateTimeToJsonDate(Match m) { string result = string.Empty; DateTime dt = DateTime.Parse(m.Groups[0].Value); dt = dt.ToUniversalTime(); TimeSpan ts = dt - DateTime.Parse("1970-01-01"); result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); return result; } }
注:如果是要将Class类Json序列化时,在实体类上面和成员上面添加一个契约,和WCF 契约一样。
举例如:////// 至爱甄选实体类 /// [Serializable] [DataContract] public class FavoriteInfo { private int _id; private string _title;////// 至爱甄选Id /// [DataMember] public int Id { set { _id = value; } get { return _id; } } [DataMember] ////// 标题 /// public string Title { set { _title = value; } get { return _title; } }}
调用方式如下:
//获取数据集,返回ListIList favoriteModelList = new PB.Favorite().GetFavoriteModelList(1, 1, ""); if (favoriteModelList!=null && favoriteModelList.Count>0) { string jsonString = JsonHelper.GetJson >(favoriteModelList); context.Response.Write(jsonString); }