Three serialization methods of C #

Source: Internet
Author: User

Serialization refers to the process of converting an object into word throttling to save it in memory, database, or file for a long time. Its main purpose is to save the object state for later use. The opposite process is called deserialization.

Serialize an object

To serialize an object, we need a serialized object, a (byte) Stream Containing the serialized object, and a formatter. Before Serialization, let's take a look at the System. Runtime. Serialization namespace. The ISerializable interface allows us to make any Class A serializable class.

If we provide the [Serializable] feature for the class ID we write, we can serialize these classes. Unless the class member is marked with [NonSerializable], serialization will serialize all the members in the class.

Serialization type
  • Binary (Stream) serialization
  • SOAP serialization
  • XML serialization
Binary (Stream) serialization:

Binary (Stream) serialization is a mechanism that writes data to the output stream so that it can be used to automatically reconstruct the corresponding object. Binary, its name implies that its required information is stored in the storage medium, and the required information requires the creation of an accurate binary copy of an object. In binary (Stream) serialization, the entire object state is saved, while XML serialization only saves some data. To use Serialization, we need to introduce System. Runtime. Serialization. Formatters. Binary namespace. The following code uses the BinaryFormatter class to serialize the string type objects in. NET.

123456789101112131415161718192021222324252627282930 using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary; namespace SerializationTest{    class Program    {        static void Main(string[] args)        {            //Serialization of String Object                      string strobj = "test string for serialization";            FileStream stream = new FileStream("C:\\StrObj.txt", FileMode.Create, FileAccess.Write ,            FileShare.None);            BinaryFormatter formatter = new BinaryFormatter();            formatter.Serialize(stream, strobj);            stream.Close();             //Deserialization of String Object            FileStream readstream = new FileStream("C:\\StrObj.txt", FileMode.Open , FileAccess.Read ,            FileShare.Read );            string readdata = (string)formatter.Deserialize(readstream);            readstream.Close();            Console.WriteLine(readdata);            Console.ReadLine();         }    }}
SOAP serialization:

SOAPProtocol is an ideal choice for information interaction between heterogeneous applications. We need to add the System. Runtime. Serialization. Formatters. Soap namespace in the application for use in. Net.SOAP serialization.SOAP serializationThe main advantage is portability.SoapFormatterSerialize an objectSOAPMessage or resolutionSOAPMessage and reconstruct the serialized object. The following code is used in. NetSoapFormatterSerializes the object of the string class.

12345678910111213141516171819202122232425262728 using System; using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Soap ; namespace SerializationTest {    class Program    {        static void Main(string[] args)        {            //Serialization of String Object                        string strobj = "test string for serialization";            FileStream stream = new FileStream("C:\\StrObj.txt", FileMode.Create, FileAccess.Write ,            FileShare.None);            SoapFormatter formatter = new SoapFormatter();            formatter.Serialize(stream, strobj);            stream.Close();            //Deserialization of String Object            FileStream readstream = new FileStream("C:\\StrObj.txt", FileMode.Open , FileAccess.Read ,            FileShare.Read );            string readdata = (string)formatter.Deserialize(readstream);            readstream.Close();            Console.WriteLine(readdata);            Console.ReadLine();        }    }}
XML serialization:

According to the description in MSDN,XML serializationConvert (serialize) the returned values of public fields, attributes, and methods of an object or parameter into XML streams following the XSD document standards. Because XML is an open standard, XML can be processed by any program. No matter what platform, XML serialization is used in a strongly typed class with public attributes and fields, its Occurrence and field are converted to serialized format (XML here) for storage or transmission."

We must addSystem. XML. SerializationReference to useXML serialization. UseXML serializationThe Foundation isXmlSerializer. The following code is used in. NetXmlSerializerClass to serialize string objects.

12345678910111213141516171819202122232425262728293031 using System;using System.IO;using System.Xml.Serialization;namespace SerializationTest{    class Program    {        static void Main(string[] args)        {            //Serialization of String Object                        string strobj = "test string for serialization";            FileStream stream = new FileStream("C:\\StrObj.txt", FileMode.Create, FileAccess.Write ,            FileShare.None);            XmlSerializer  xmlserializer = new XmlSerializer(typeof(string));            xmlserializer.Serialize(stream, strobj);            stream.Close();            //Deserialization of String Object            FileStream readstream = new FileStream("C:\\StrObj.txt", FileMode.Open , FileAccess.Read ,            FileShare.Read );            string readdata = (string)xmlserializer.Deserialize(readstream);            readstream.Close();            Console.WriteLine(readdata);            Console.ReadLine();         }    }}
What is a formatter?

OneFormatterUsed to determine the sequence format of an object. They aim to serialize an object on the network into a suitable format before it is transmitted. They provideIFormatterInterface. In. NET, two formatting classes are provided:BinaryFormatterAndSoapFormatter, They all inheritIFormatterInterface.

Use serialization

Serialization allows developers to save the state of an object and reconstruct the object as needed. It also supports object storage and data exchange. Through serialization, developers can use Web Service to send objects to remote applications, transfer objects from one domain to another, transmit an object in XML format and pass the firewall, or maintain security or user-specific information between applications.

Related Article

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.