In daily life, we often use the process of serializing a T type thing into Json and then returning the bound data to the page. In every interview, I am probably asked how to serialize? The answer is always encapsulated at the bottom level, forget it, let’s make a simple chestnut for fun, so as to block the interviewer’s mouth.
When serializing and deserializing, the object DataContractJsonSerializer is mainly used, and then combined with MemoryStream, it is ok.
Without further ado, let’s start with a simple + generic chestnut, and then we will gradually improve it:
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; } } }
Then we write a class to test:
//[Serializable] public class Student { public string StudentId { get; set; } public string Name { get; set; } public int age { get; set; } public string Address { get; set; } }
Test code:
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 }
Watch the results:
I don’t know if you haven’t noticed that in the past, all the objects we could serialize had to have the [Serializable] feature, but I checked it out in the student class, why? Write one yourself and run it to see what happens. The reason is not explained. Please refer to Baidu University. Lazy kids can wait until the poster is in a better mood and update the blog! In addition, in this example, only simple types are serialized, and complex situations are not considered. The poster will update the blog depending on his mood.
The above is the content of .Net - using DataContractJsonSerializer for basic serialization and deserialization operations. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!