. net--use DataContractJsonSerializer for serialization and deserialization of basic operations

Source: Internet
Author: User
in the ordinary, we often use a t type of things, serialized into JSON and then return bound data to the page such a process. Every interview, probably was asked how to serialize it? The answer is always the bottom package good, calculate, or do a simple chestnut play it, or plug the interviewer's mouth.

For serialization and deserialization, the main use of the object DataContractJsonSerializer, and then with MemoryStream, OK.

Not much to say, first to a version of the simple + generic chestnut, and then we will gradually improve:

  public static class JsonConvert {//<summary>//Converts the obj to JSON. </summary>//<typeparam name= "T" ></typeparam>//<param name= "T" >the t.</p aram>//<returns>System.String.</returns>//<remarks>editor:v-liuhch createtime:201 5/6/21 21:40:55</remarks> public static string convertobjtojson<t> (T t) {Datacontrac            Tjsonserializer 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) {//Handle exception yourself return null; }}///<summary>//JsONS the deserialize. </summary>//<typeparam name= "T" ></typeparam>//<param name= "Strjson" >the ST R json.</param>//<returns> ' 0.</returns>//&LT;REMARKS&GT;EDITOR:V-LIUHCH Createtime: 2015/6/21 21:46:37</remarks> public static T jsondeserialize<t> (String strjson) where T:clas S//constraint T is class, can also be relaxed type, here is just an example, write fun, Aubagne, here can be changed {datacontractjsonserializer ser = new Datacontractjsonseri            Alizer (typeof (T));                try {using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (Strjson))) {T obj = ser.                    ReadObject (MS) as T;                return obj;            }} catch (IOException e) {//Handle exception yourself return null; }                   }    }

Then we write a class test under:

[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 = "Shi", Name = "paddy field as Ya", age = +, Address = "Chaoyang District, Beijing"            };                #region Serialization Test String Strstudentjson = Jsonconvert.convertobjtojson<student> (Student);                            Response.Write (Strstudentjson);                #endregion #region deserialization test//{"Address": "Chaoyang District, Beijing", "Name": "paddy fields such as Ya", "StudentID": "Shi", "Age": 20}                String Strjson = "{\" address\ ": \" Beijing chaoyang \ ", \" name\ ": \" paddy fields such as Ya \ "," 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}

The result of onlookers:


I don't know, but you didn't notice that the object that we were able to serialize before is going to be [Serializable], but on the student class I'm just taking it off, why? Write yourself a run to see what happens, the reason is not explained, please refer to the University of Baidu. Micro-lazy children's shoes can wait for the landlord mood is good update blog! in addition, in this case just the simple type is serialized, the complex situation is not considered, the landlord will look at the mood and more blog.

The above is. net--use DataContractJsonSerializer for serialization and deserialization of the basic operation of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.