標籤:javascrip rem date style utf8 獨立 res throw 表示
JSON(JavaScript Object Notation)JavaScript對象標記法,它是一種基於文本,獨立於語言的輕量級資料交換格式。在現在的通訊中,較多的採用JSON資料格式,JSON有兩種表示結構,對象和數組,JSON 資料的書寫格式是:成對的名稱和數值。
在vs解決方案中以前採用xml樹的形式,組織項目的結構。在新的.net core中,項目的解決方案採用json作為項目的結構說明。
在.net的前後台資料互動中,採用序列化對象為json,前端ajax接受傳輸資料,還原序列化為對象,在頁面對資料進行渲染。有關json的相關內容就不再贅述,在.net中序列化的類主要採用DataContractJsonSerializer類。
現在提供一個較為通用的json的序列化和還原序列化的通用方法。
1.json的序列化:
/// <summary> /// 將對象序列化為JSON /// </summary> /// <typeparam name="T">序列化的類型</typeparam> /// <param name="t">需要序列化的對象</param> /// <returns>序列化後的JSON</returns> public static string JsonSerializer<T>(T t) { if (t == null) throw new ArgumentNullException("t"); string jsonString; try { var ser = new DataContractJsonSerializer(typeof(T)); var ms = new MemoryStream(); ser.WriteObject(ms, t); jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); //替換Json的Date字串 const string p = @"\\/Date\((\d+)\+\d+\)\\/"; var matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); var reg = new System.Text.RegularExpressions.Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); } catch (Exception er) { throw new Exception(er.Message); } return jsonString; }
2.json的還原序列化:
/// <summary> /// 將JSON還原序列化為對象 /// </summary> public static T JsonDeserialize<T>(string jsonString) { if (string.IsNullOrEmpty(jsonString)) throw new Exception(jsonString); //將"yyyy-MM-dd HH:mm:ss"格式的字串轉為"\/Date(1294499956278+0800)\/"格式 const string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; try { var matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); var reg = new System.Text.RegularExpressions.Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); var ser = new DataContractJsonSerializer(typeof(T)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); var obj = (T)ser.ReadObject(ms); return obj; } catch (Exception ex) { throw new Exception(ex.Message, ex); } }
以上是一個較為簡單的json序列化和還原序列化方法。
DotNet的JSON序列化與還原序列化