JavaScriptSerializer class object serialized to Json,json deserialization object

Source: Internet
Author: User
Tags serialization

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize data passed between the browser and the WEB server. It's plain to be able to transfer a C # object directly to the foreground page as a JavaScript object. The reference to add System.Web.Extensions.dll. The class is located under the System.Web.Script.Serialization namespace.

First, the attribute

Maxjsonlength Gets or sets the maximum length of the JSON string accepted by the JavaScriptSerializer class.
Recursionlimit Gets or sets the limit that is used to constrain the number of object levels to be processed.

Second, the 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 with a JavaScriptSerializer instance.
Serialize is overloaded. Converts an object to a JSON string.

To give an example, the main is to understand the serialize and deserialize two methods, 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 = JSS. Serialize (P); Serialized into JSON person p1 = JSS.  Deserialize<person> (JSON);     Then deserialize to the person object note that this method requires the target class to have a parameterless constructor//return JSON (JSON, "Text/json");            Very useful, but the return is the string, return to the foreground to parse to become a JavaScript object. Return Json (New {Id = P1. Id, Name = p1. Name, age = P1.  Age}, "Text/json");//If this is the case, return to JavaScript is no longer parsed, directly is the 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 }    }

Foreground HTML code:

try 4 basic methods and properties

Class Program {static void Main (string[] args) {//method//Registerconverters using J              Avascriptserializer instance to register a custom converter.             Properties//Recursionlimit Gets or sets the limit that is used to constrain the number of object levels to be processed.            JavaScriptSerializer JSS = new JavaScriptSerializer (); Console.WriteLine (JSS.   Maxjsonlength); The default accept maximum length is 2097152 this is to accept the maximum length of the JSON string, what will be the consequences of super-long? Try the JSS.            Maxjsonlength = 1;            Person p = new person (1, "Guan Yu", 21); String json = JSS.     Serialize (P); Serializes an object into a JSON string//Here is an error when serializing or deserializing using JSON javascriptserializer.            The length of the string exceeds the value set for the Maxjsonlength property. Jss.                        Maxjsonlength = 2097152; Serializes string json = JSS.             Serialize (P);    Console.WriteLine (JSON); Output {"Id": 1, "Name": "Guan Yu", "Age": 21} ' This is the JSON format//deserialization deserialize person P2 = JSS.            Deserialize<person> ("{\" id\ ": 1,\" name\ ": \" Guan yu \ ", \" age\ ": 21}"); Console.WriteLine (P2. Id + "" + P2. NaMe + "" + P2.    Age); Output 1 Guan Yu//deserialize's non-generic notation person p3 = JSS.  Deserialize ("{\" id\ ": 1,\" name\ ": \" Guan yu \ "," age\ ":" +} ", typeof (person)) as a person; Note that this method returns the object class, so it is forced to convert to the person class Console.WriteLine (P3. Id + "" + p3. Name + "" + p3.    Age); Likewise output 1 Guan Yu, object obj = JSS.    Deserializeobject ("{\" id\ ": 1,\" name\ ": \" Guan yu \ ", \" age\ ": 21}");    Converts a JSON character to an object type//person P4 = obj as person; This line of code is converted to a null person P4 = JSS. P4.     Converttotype<person> (obj); This method is used in this way, knowing that the deserializeobject conversion will be null so write another one Console.WriteLine (P4.     Name); Output Guan Yu//non-generic version person P5 = JSS.            Converttotype (obj,typeof) as person; Console.WriteLine (P5.     Name);        Output of Guan Yu Console.readkey (); }    }

  Implementing a custom Converter

Serializes the specified data type to JSON. The Serialize method is a recursive method that recursively serializes the properties of an object, so a "circular reference" exception is often encountered when serializing a complex object, such as a DataTable, and a converter is required to customize for complex types. Here is the converter for the DataTable, which is the principle of converting a DataTable into a dictionary list before serializing:

All custom converters are inherited from JavaScriptConverterand implement Serialize, deserialize methods, and Supportedtypes properties. Where the Supportedtypes property is used to enumerate the types supported by this converter.

    Class Program {static void Main (string[] args) {datatable dt = new DataTable (); Dt.            Columns.Add ("Id"); Dt.            Columns.Add ("Name"); Dt.            Columns.Add ("Age"); Dt.            Rows.Add (1, "Guan Yu", 21); Dt.            Rows.Add (2, "Liu Bei", 22); Dt.            Rows.Add (3, "Zhang Fei", 20);            JavaScriptSerializer JSS = new JavaScriptSerializer (); The method for registering converters, for complex conversions, requires registration to JavaScriptSerializer JSS in addition to implementation.            Registerconverters (new javascriptconverter[] {new Datatableconverter ()}); String Strjson = JSS.            Serialize (DT);            Console.WriteLine (Strjson); Output {"Rows": [{"id": "1", "Name": "Guan Yu", "Age": "},{", "id": "2", "Name": "Liu Bei", "Age": "},{" id ":" 3 "," name ":" Zhang Fei "," Age ":"        "}]} console.readkey (); }}///<summary>//DataTable JSON conversion class///</summary> public class DATATABLECONVERTER:JAVASC Riptconverter {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 Dt.                Rows) {dictionary<string, object> row = new dictionary<string, object> (); foreach (DataColumn dc in dt. Columns) {row. ADD (DC. ColumnName, DR[DC.                ColumnName]); } rows.            ADD (row);            } result["Rows"] = rows;        return result; } public override object Deserialize (idictionary<string, object> dictionary, type type, JavaScriptSerializer        Serializer) {throw new NotImplementedException ();   }///<summary>//Get the type 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 Javascriptser            Ializer (); Console.WriteLine (JSS.  Recursionlimit);            The default serialization level is P1 = new person (1, "Liu Bei", 24);            P1.P = new Person (2, "Guan Yu", 23);            P1.P.P = new Person (3, "Zhang Fei", 21); String Strjson = JSS.            Serialize (p1);            Console.WriteLine (Strjson);            Output {"Id": 1, "name": "Liu Bei", "Age": "P": {"id": 2, "name": "Guan Yu", "Age": "P": {"id": 3, "name": "Zhang Fei", "Age": "P": null}} Now reduce the level to 1 JSS.            Recursionlimit = 1; String strJson2 = JSS. Serialize (p1);//This line of code is reported as abnormal, showing that it has exceeded recursionlimit.        This is the function of this property//finally a feature, such as if I have a certain property do not want it to serialize, then you can set add Console.readkey ();        }} 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;}    Inside a person, public person p {get; set;} }
[Scriptignore] Disables the serialization of a property
Class program    {        static void Main (string[] args)        {            JavaScriptSerializer JSS = new JavaScriptSerializer ( );            Person p = new person (1, "Liu Bei", +);            Console.WriteLine (JSS. Serialize (P));            File.writealltext (@ "D:\123.txt", JSS. Serialize (P));  Output {"Id": 1, "Age": Console.readkey}            ();}    }    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;}        [Scriptignore]        public string Name {get; set;}         public int Age {get; set;}    }

JavaScriptSerializer class object serialized to Json,json deserialization object

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.