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 );