Brief discussion on object serialization technology in. Net

Source: Internet
Author: User
Tags object serialization

Brief discussion on object serialization technology in. Net
  • 2009-03-11Read2756 Comments 2 Serialization is the process of converting an object's state into a format that can be persisted or transmitted. Relative to serialization is deserialization, which transforms a stream into an object. Together, these two processes make it easy to store and transfer data. For example, you can serialize an object and then use HTTP to transfer the object between the client and the server over the Internet. Conversely, deserialization reconstructs an object based on a stream. The object can also be serialized and saved locally, and run again when the object can be "recovered" from the local file to the state before the serialization. There are several ways to serialize in. NET: binary serialization XML Serialization SOAP SerializationBinary SerializationThe so-called binary serialization, refers to the object is serialized after the binary form. Binary serialization is implemented through the BinaryFormatter class, which is located under the System.Runtime.Seria2lization.Formatters.Binary namespace.Serialization of XMLThe so-called XML serialization, refers to the object after the serialization of the result is in XML form. Saving XML serialization is done through the XmlSerializer class, which is located under the System.Xml.Serialization namespace.SOAP SerializationThe so-called SOAP serialization refers to the result of object serialization that conforms to the SOAP protocol, which can be transmitted through the SOAP protocol (unaware of the SOAP protocol?). Baidu a bit). SOAP serialization is implemented through the SoapFormatter class, which is located under the System.Runtime.Serialization.Formatters.Soap namespace, and you need to be aware of the need to manually add a reference to the namespace. As shown in: Write a class below for serialization and deserialization, the code for this class is as follows:<textarea class="c-sharp:nogutter:nocontrols" name="code" rows="15" cols="50"></textarea>Here is the code that is serialized and deserialized with the above three classes, respectively:<textarea class="c-sharp" name="code" rows="15" cols="50"></textarea>This program works as follows: visible through the above three classes can be implemented to save the object serialization, and can be deserialized back to the object before the serialization of the State (this is the meaning of the serialization, can save the state of the object runtime and can also be restored). If you run the above code will create three files in the C packing directory, respectively, MyObject.dat, Myobject.soap and Myobject.xml files, Because MyObject.dat is a binary file, it is not possible to view the contents of a file, but we can open the two files of Myobject.soap and myobject.xml to compare the differences. The suffix of the Myobject.soap file is. soap, but can still be opened with Notepad, here is the contents of the Myobject.soap file:<textarea class="xhtml" name="code" rows="15" cols="50"></textarea>The Myobject.xml file can also be opened in Notepad with the following contents:<textarea class="xhtml" name="code" rows="15" cols="50"></textarea>A friend who is familiar with the SOAP protocol knows that it conforms to the SOAP protocol, and the Myobject.xml file is undoubtedly a file that conforms to the XML specification, as it myobject.soap the contents of the file. A few notes to the code: 1, if you use the BinaryFormatter class or the SoapFormatter class to achieve serialization, be sure to add the serializable attribute to the class, as shown in the code:<textarea class="c-sharp" name="code" rows="15" cols="50"></textarea>If you do not add this property to the object being serialized, the exception is reported when serializing using the BinaryFormatter class or the SoapFormatter class, but you can use the XmlSerializer class to serialize the object without this property. 2, in addition, if you do not want to serialize a field, you can add the NonSerialized property, so that the value of this field will not be saved at serialization, for example, do not want to serialize the name of the field, you can write the following code:<textarea class="c-sharp" name="code" rows="15" cols="50"></textarea>Running the program again will result in the following: There is a yellow bottom line, because the name field is not serialized, so the binary serialization and the SOAP serialization after the re-ordering will not get the original value. 3. Finally, it is necessary to state that the SoapFormatter class is obsolete in. net3.5, and Microsoft recommends using the BinaryFormatter class to serialize and deserialize. Llllllllllll???????????????????? Use Json.NET to serialize the required data when we do development, we often need to deal with JSON data format, such as Web development, many times, the data is passed to the page through JSON, and then processed. When using Json, we often involve the use of several serialized objects: Datacontractjsonserializer,javascriptserializer and Json.NET. Most people will choose performance and versatility better json.net, this is not Microsoft Class Library, but an open-source world-class JSON Operation class Library, from the performance comparison below, can see the performance benefits of one of its. Json.NET can serialize or deserialize various types of. NET data, and another advantage of it is that you can configure the attribute property, specify the name of the output property, or whether it is output, which I like very much. JSON (JavaScript object Notation,javascript) is a lightweight data interchange format. JSON is a collection of "name-value pairs". The structure consists of braces ' {} ', brackets ' [] ', comma ', ', ' colon ': ', ' double quotation marks ' "", consisting of a data type of object,number,boolean,string,array, NULL, etc. 1. Using JSON data in the Web   in my Mvc+easyui-based Web development framework, the Web interface layer uses AJAX to get the data needed, and then binds it to a tree list control or other interface control, in some of the previous web framework essay series, I've covered a lot of JSON-formatted operations. 1) Experience summary of Web development framework based on MVC4+EASYUI (3)-building menu data using JSON entity classes 2) Mvc4+easyui-based Web development Framework Experience Summary (2)-Build a Web interface using Easyui tree controls like in the MVC view, After the JSON data from the Web request is initialized, the code for the tree control follows//initializes the Organization list Functioninitdepttreeview () {$ ("#loading"). Show (); $ (' #treeDept '). Tree ({ url:  '/user/[email protected]["UserId"] ', onclick: function (node) {loaddatabyou (node.id);}}); $ ("#loading"). FadeOut (500); } or the user role's initialization interface Code $ (' #lbxRoles '). empty (); $.getjson ("/role/getrolesbyuser?r=" + math.random () + "&userid=" + info.id, function (JSON) {$.each (JSON),  function (I, Item) {$ (' #lbxRoles '). Append (' <option VAlue= "' + item.id + '" > ' + Item. Name + ' </option> '); }); }); As mentioned earlier, Json.NET has a property configuration feature that allows you to specify whether a property is output, or the name of the output is escaped, and so on. By default, the field names in the results of json.net are consistent with the names of the properties in the class, and if you want to customize the field names after serialization, you can use Jsonproperty. We know that in Easyui's tree control, its data format, in addition to an ID and text is necessary, many of its properties are optional, that is, in JSON, you can not output a property of the content. The output of a property can be ignored by configuring [Jsonproperty (Nullvaluehandling = Nullvaluehandling.ignore)], if the value of this property is null. Tree control data also has a checked property, if there is no escape function, we need to specify the property is checked, and checked is a C # inside the reserved keyword, can not be used, then there is no way. The json.net provides a configuration attribute for the Escape function, which solves the problem well, as shown below. [Jsonproperty (PropertyName =  "Checked", nullvaluehandling =nullvaluehandling.ignore)] publicbool? Checked { get; set;} So the entire Easyui tree data object information, in C # can be defined as follows (here you can ignore the definition of DataContract, DataMember). <summary>///defines Easyui tree related data, facilitates the controller to generate JSON data for delivery  ///</summary>[datacontract] [Serializable]  publicclasseasytreedata { ///<summary>///id ///</summary>[datamember]  Publicstringid { get; set;}  ///<summary>///Node name  ///</summary>[Datamember] publicstringtext { get; set;}  ///<summary>///whether to expand  ///</summary>[jsonproperty (nullvaluehandling = Nullvaluehandling.ignore)] [Datamember] publicstringstate { get; set;}  ///<summary>///icon Style  ///</summary>[datamember][jsonproperty (NullValueHandling = Nullvaluehandling.ignore)]publicstringiconcls { get; set;} [Jsonproperty (propertyname =  "Checked", nullvaluehandling =nullvaluehandling.ignore)] [DataMember (name= "checked")] publicbool? Checked { get; set;}  ///<summary>///Child node Collection  ///</summary>[DataMember] publicList<EasyTreeData> Children { get; set;} Using the entity classes on, and using Json.NET to serialize our data, we might get the JSON data below. [{id:  "-1", text:  "None", state:  "open", Checked: true,children: []}, {id:  "6", text:  " General manager ", state: " open ", iconcls: " Icon-group ", Children: []}] we can see from the JSON data above that the checked attribute is successfully converted to the checked name attribute, Marked as [JsoNproperty (nullvaluehandling = Nullvaluehandling.ignore)]&nbsp, and a null-valued property will not appear in the JSON string. In some cases, this is exactly what we need.  2, in interface development The use of Jsonapi interface, a large number of JSON data used, not only many of the returned data is using JSON expression, and its post data, but also most of the use of JSON data format, such as in my first two essays "C # Development Portal and Applications (5)-User group information management"  , Many of the interfaces used in the C # development Portal and Applications (4)-Attention to user list and details management are using JSON data. The JSON data that returns the list of followers is shown below. {"Total": 2, "Count": 2, "data": {"OpenID": ["", "OPENID1", "OPENID2"]}, "Next_openid": "Next_openid"} Create user group, return data format as follows, The same is the JSON data. {  "group": {  "id": 107,  "name": "Test"}} The conversion from JSON string to the corresponding entity object can be accomplished through the conversion of the Json.NET-based JSON data below. <summary>///JSON string Manipulation Helper class//</summary>public class jsonhelper<t> where T:class, new () {& nbsp;///<summary>///Check the returned record, if no error is returned, or if the result prompt succeeds, do not throw an exception///</summary>///<param name= "Content" > The returned result </param>///<returns></returns>private static bool Verifyerrorcode (string content) { if ( Content. Contains ("Errcode")) { errorjsonresult errorresult = Jsonconvert.deserializeobject<errorjsonresult > (content);  //The exception is logged for a non-successful operation because some operations return a normal result ({"Errcode": 0, "errmsg": "OK"}) if (Errorresult!= null& & ErrorrEsult.errcode!=returncode. Request succeeded) {string error = string. Format ("The request has an error! Error code: {0}, Description: {1} ", (int) errorresult.errcode, errorresult.errmsg); Logtexthelper.error (Errorresult);  thrownewweixinexception (error);//Throw Error}} returntrue; } ///<summary>///Convert the JSON string to a specific object///</summary>///<param name= "url" > return the link address of the JSON data </ param>///<returns></returns>public static T convertjson (string url) {Httphelper helper =  Newhttphelper (); String Content =helper. gethtml (URL); Verifyerrorcode (content);  t result = jsonconvert.deserializeobject<t> (content);  Returnresult; And if you want to convert the object to data in JSON string format, then the code is simple. Jsonconvert.serializeobject (obj, formatting.indented); 

    This article is from the "Zhou Gong (Zhou Jinchao) column" blog, please be sure to keep this source http://zhoufoxcn.blog.51cto.com/792419/162943

    2012-05-12 can be transmitted through the SOAP protocol (do not know the SOAP protocol?). Baidu a bit) haha, I really do not know what this agreement, just heard that the results really go to Baidu to know more. Ha ha.....

Brief discussion on object serialization technology in. Net

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.