在平常中,我們常會用到將一個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的。