在平常中,我們經常會用到將一個T類型的東西,序列化成Json然後返回綁定資料到頁面這樣一個過程。每次面試,大概都被問到怎麼序列化的呀?回答總是底層封裝好的,算啦,還是做個簡單栗子玩玩兒吧,也好堵住面試官的嘴。
進行序列化和還原序列化的時候,主要用到對象DataContractJsonSerializer,然後再配合MemoryStream,就ok啦。
不多說,先來一版簡單的+泛型的栗子,之後,我們會逐步改進:
public static class JsonConvert { /// <summary> /// Converts the obj to json. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t">The t.</param> /// <returns>System.String.</returns> /// <remarks>Editor:v-liuhch CreateTime:2015/6/21 21:40:55</remarks> public static string ConvertObjToJson<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(t.GetType()); try { using (MemoryStream ms=new MemoryStream()) { ser.WriteObject(ms,t); string strJson=Encoding.UTF8.GetString(ms.ToArray()); return strJson; } } catch (IOException) { //自己處理異常吧 return null; } } /// <summary> /// Jsons the deserialize. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="strJson">The STR json.</param> /// <returns>``0.</returns> /// <remarks>Editor:v-liuhch CreateTime:2015/6/21 21:46:37</remarks> public static T JsonDeserialize<T>(string strJson) where T:class //約束T為class,也可以放寬類型,這裡只是個例子,寫著玩兒的,歐巴們,此處可改 { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); try { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) { T obj = ser.ReadObject(ms) as T; return obj; } } catch (IOException e) { //自己處理異常吧 return null; } } }
然後我們寫個類測試下:
//[Serializable] public class Student { public string StudentId { get; set; } public string Name { get; set; } public int age { get; set; } public string Address { get; set; } }
測試代碼:
protected void Page_Load(object sender, EventArgs e) { Student student = new Student() { StudentId = "110", Name = "水田如雅", age = 20, Address = "北京朝陽區" }; #region 序列化測試 string strStudentJson = JsonConvert.ConvertObjToJson<Student>(student); Response.Write(strStudentJson); #endregion #region 還原序列化測試 //{"Address":"北京朝陽區","Name":"水田如雅","StudentId":"110","age":20} string strJson = "{\"Address\":\"北京朝陽區\",\"Name\":\"水田如雅\",\"StudentId\":\"110\",\"age\":20}"; Student newStudent = JsonConvert.JsonDeserialize<Student>(strJson); Response.Write(@"<br/><br/>" + newStudent.Address + "<br/>" + newStudent.Name + "<br/>" + newStudent.StudentId + "<br/>" + newStudent.age.ToString()); #endregion }
圍觀下結果:
不知親你又沒有注意到,以前我們可以序列化的對象都是要打上[Serializable]這一特性的,但是在student類上我卻注掉了它,why? 自己寫一個運行下看看會發生啥吧,原因也不解釋,請參考百度大學。微懶的童鞋可以坐等樓主心情好了更新blog!另外,本例中只是對簡單類型進行了序列化,複雜情況未進行考慮,樓主會看心情再更blog的。
以上就是.Net——使用DataContractJsonSerializer進行序列化及還原序列化基本操作 的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!