Newtonsoft. JSON: serialization and deserialization of ASP. NET Json,

Source: Internet
Author: User

Newtonsoft. JSON: serialization and deserialization of ASP. NET Json,

The class library we use is Newtonsoft. Json, which can be downloaded using the NuGet package in the VS tool.

I. Object conversion to json-serialization

Public class Student {public int ID {get; set;} public string Name {get; set;} public int Age {get; set ;}// the first type: single Entity class Student s = new Student (); s. age = 18; s. ID = 1; s. name = "James"; string json = Newtonsoft. json. javaScriptConvert. serializeObject (s); // serialized object (object to json) // The second type: list <T> generics are the same as the above method List <Student> list = new List <Student> (); for (int I = 1; I <5; I ++) {Student stu = new Student (); stu. age = I + 12; stu. ID = I; stu. name = "No. "+ I. toString (); list. add (stu);} json = Newtonsoft. json. javaScriptConvert. serializeObject (list );

 

Ii. Convert json to object-deserialization

// Json only contains one data record, including JavaScriptObject = (JavaScriptObject) JavaScriptConvert. deserializeObject (json); string Name = obj ["Name"]. toString (); // retrieves a certain field Response. write (Name); // json only one data Student MS = (Student) JavaScriptConvert. deserializeObject (JavaScriptConvert. serializeObject (obj), typeof (Student); // json to object Response. write (ms. name); // json contains multiple data records. JavaScriptArray javascript = (JavaScriptArray) JavaScriptConvert. deserializeObject (json); List <Student> slist = new List <Student> (); for (int I = 0; I <javascript. count; I ++) {JavaScriptObject temp = (JavaScriptObject) javascript [I]; Student model = (Student) JavaScriptConvert. deserializeObject (JavaScriptConvert. serializeObject (temp), typeof (Student); slist. add (model );}

// Method 4.0
List <Student> slist = JsonConvert. DeserializeObject <List <Student> (json );
Response. Write (slist [0]. Name );

 

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.