The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize data passed between the browser and the web server. To put it bluntly, it is possible to directly transmit a C# object to the foreground page and become a javascript object. Reference to add. This class is located under the namespace.
1. Attributes
MaxJsonLength Gets or sets the maximum length of the JSON string accepted by the JavaScriptSerializer class.
RecursionLimit Gets or sets a limit to the number of object levels to be processed.
2. Method
ConvertToType<(Of <(T>)>) Converts the given object to the specified type.
Deserialize<(Of <(T>)>) Converts the specified JSON string to an object of type T.
DeserializeObject Converts the specified JSON string to an object graph.
RegisterConverters registers a custom converter using JavaScriptSerializer instance.
Serialize is overloaded. Converts an object to a JSON string.
Let me give you an example, mainly to understand the two methods Serialize and Deserialize, controller code:
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 = (p); //Serialize to JSON Person p1 = <Person>(json); //Deserialize it to a Person object. Note that this method requires the target class to have a parameter constructor. //Return Json(json, "text/json"); //It's very useful, but the returned string is ultimately a string. You have to parse it when you return to the foreground before you can become a javascript object. return Json(new { Id = , Name = , Age = }, "text/json");//If you write this way, you don’t need to parse it again when you return to javascript, it is just a javascript object } } public class Person { public Person() { } public Person(int id, string name, int age) { = id; = name; = age; } public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
Front desk HTML code:
<html> <head> <title>javascriptSerializerClass Test</title> <script src="/jQuery.1.8." type="text/javascript"></script> <script type="text/javascript"> $(function () { $(":button").click(function () { $.ajax({ url: "/Home/GetJson", dataType: "json", type: "post", success: function (response) { // var data = (response); // $("#Id").text(); // $("#Name").text(); // $("#Age").text(); $("#Id").text(); $("#Name").text(); $("#Age").text(); } }) }) }) </script> </head> <body> <ul> <li ></li> <li ></li> <li ></li> </ul> <input type="button" value="confirm" /> </body> </html>
Try 4 basic methods and attributes
class Program { static void Main(string[] args) { // method // RegisterConverters registers a custom converter using JavaScriptSerializer instance. //property // RecursionLimit Gets or sets a limit to the number of object levels to be processed. JavaScriptSerializer jss = new JavaScriptSerializer(); (); //The maximum length accepted by default is 2097152. This is the maximum length of accepting JSON strings. What are the consequences of being too long? Try it = 1; Person p = new Person(1,"Guan Yu",21); //string json = (p); //Serialize the object into a Json string //An error occurred when using JSON JavaScriptSerializer for serialization or deserialization. The length of the string exceeds the value set for the maxJsonLength property. = 2097152; //Serialization string json = (p); (json); //Output {"Id":1,"Name":"Guan Yu","Age":21}`This is the Json format //Deserialize Deserialize Person p2 = <Person>("{\"Id\":1,\"Name\":\"Guan Yu",\"Age\":21}"); ( + " " + + " " + ); //Output 1 Guan Yu 21 //Non-generic writing of Deserialize Person p3 = ("{\"Id\":1,\"Name\":\"Guan Yu",\"Age\":21}",typeof(Person)) as Person; //Note that this method returns object class, so it must be cast to Person class ( + " " + + " " + ); //Same output 1 Guan Yu 21 object obj = ("{\"Id\":1,\"Name\":\"Guan Yu",\"Age\":21}"); //Convert Json characters to Object type //Person p4 = obj as Person; //The p4 converted to this line of code is null Person p4 = <Person>(obj); //So this method is used like this. I know that the DeserializeObject conversion will be null, so I wrote another one (); //Output Guan Yu //Non-generic version Person p5 = (obj,typeof(Person)) as Person; (); //Output Guan Yu (); } }
Implement custom converter
Serializes the specified data type to Json. The Serialize method is a recursive method that recursively serializes the properties of an object. Therefore, when serializing a complex object (such as DataTable), there is often an exception of "loop reference". At this time, you need to customize a converter for complex types. The following is the converter of DataTable. The principle is to convert DataTable into a dictionary list and then serialize it:
All custom converters must inherit from JavaScriptConverter and implement Serialize, Deserialize methods, and SupportedTypes properties, where SupportedTypes properties are used to enumerate the types supported by this converter.
class Program { static void Main(string[] args) { DataTable dt = new DataTable(); ("Id"); ("Name"); ("Age"); (1, "Guan Yu", 21); (2, "Liu Bei", 22); (3, "Zhang Fei", 20); JavaScriptSerializer jss = new JavaScriptSerializer(); //The method of registering a converter is used for complex conversions, in addition to implementation, it also requires registration to JavaScriptSerializer. (new JavaScriptConverter[] { new DataTableConverter() }); string strJson = (dt); (strJson); //Output {"Rows":[{"Id":"1","Name":"Guan Yu","Age":"21"},{"Id":"2","Name":"Liu Bei","Age":"22"},{"Id":"3","Name":"Zhang Fei","Age":"20"}]} (); } } /// <summary> /// DataTable JSON conversion class /// </summary> public class DataTableConverter : JavaScriptConverter { public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { DataTable dt = obj as DataTable; Dictionary<string, object> result = new Dictionary<string, object>(); List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); foreach (DataRow dr in ) { Dictionary<string, object> row = new Dictionary<string, object>(); foreach (DataColumn dc in ) { (, dr[]); } (row); } result["Rows"] = rows; return result; } public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// Get the types supported by this converter /// </summary> public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(DataTable) }; } } }
Limit the hierarchy of serialization
class Program { static void Main(string[] args) { JavaScriptSerializer jss = new JavaScriptSerializer(); (); //The default serialization level is 100 Person p1 = new Person(1, "Liu Bei", 24); = new Person(2, "Guan Yu", 23); = new Person(3, "Zhang Fei", 21); string strJson = (p1); (strJson); //Output {"Id":1,"Name":"Liu Bei","Age":24,"p":{"Id":2,"Name":"Guan Yu","Age":23,"p":{"Id":3,"Name":"Zhang Fei","Age":21,"p":null}}} //Reduce the level to 1 now = 1; string strJson2 = (p1);//This line of code reports an exception and displays that RecursionLimit has exceeded. This is what this attribute does // Finally, let’s talk about a feature, for example, if I have a certain property that does not want it to be serialized, then I can set the addition (); } } public class Person { public Person() { } public Person(int id, string name, int age) { = id; = name; = age; } public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } //Nest a Person inside public Person p { get; set; } }
[ScriptIgnore] Prohibit serialization of a certain attribute
class Program { static void Main(string[] args) { JavaScriptSerializer jss = new JavaScriptSerializer(); Person p = new Person(1,"Liu Bei",24); ((p)); (@"D:\", (p)); //Output {"Id":1,"Age":24} (); } } public class Person { public Person() { } public Person(int id, string name, int age) { = id; = name; = age; } public int Id { get; set; } [ScriptIgnore] public string Name { get; set; } public int Age { get; set; } }
The above is all the content of this article. I hope it will be helpful to everyone. Thank you for your support!