在平常中,我们经常会用到将一个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的。see u~
----------------------------------------------------------第二天--------------------------------------------
补上答案:
https://msdn.microsoft.com/zh-cn/library/bb412179.aspx
时间: 2024-10-06 02:08:36