The serialization and deserialization of the JavaScriptSerializer class are used inside the asynchronous communication layer to serialize and deserialize the data transmitted between the browser and the Web server. To put it bluntly, a C # object can be directly transferred to the front-end page to become a javascript Object. To add a reference to System. Web. Extensions. dll. This class is located in the namespace System. Web. Script. Serialization.
I. Attributes
MaxJsonLength gets or sets the maximum length of the JSON string accepted by the JavaScriptSerializer class.
RecursionLimit gets or sets the limit on the number of objects to be processed.
Ii. Method
ConvertToType <(Of <(T>) converts a given object to a specified type.
Deserialize <(Of <(T>) converts a specified JSON string to a T-type object.
DeserializeObject converts a specified JSON string to an object graph.
RegisterConverters uses the JavaScriptSerializer instance to register a custom converter.
Serialize is overloaded. Converts an object to a JSON string.
Here is an example of two methods: Serialize and Deserialize. The controller code is as follows:
Public class HomeController: Controller {public ActionResult Index () {return View ();} public ActionResult GetJson () {JavaScriptSerializer jss = new JavaScriptSerializer (); Person p = new Person (1, "Zhang Fei", 20); string json = jss. serialize (p); // Serialize to JSON Person p1 = jss. deserialize
(Json); // deserialize the object to the Person object. Note that this method requires the target class to have a constructor. // return Json (json, "text/json"); // It is easy to use, however, the returned result is a string, and the returned result must be parsed at the front end to become a javascript Object. Return Json (new {Id = p1.Id, Name = p1.Name, Age = p1.Age}, "text/json"); // if this is the case, no need to parse the response to javascript. It is directly a javascript Object} public class Person {public Person () {} public Person (int id, string name, int age) {this. id = id; this. name = name; this. age = age;} public int Id {get; set;} public string Name {get; set;} public int Age {get; set ;}}
Front-end HTML code:
JavascriptSerializer class test