Serialization is the process of converting the object state to a format that can be maintained or transmitted. In contrast to serialization, deserialization converts a stream into an object. These two processes can be combined to easily store and transmit data. For example, you can serialize an object and Use HTTP to transmit the object between the client and the server over the Internet. Conversely, deserialization reconstructs an object based on the stream. In addition, the object can be serialized and saved to the local device. During re-running, the object can be "restored" from the local file to the state before serialization.
There are several serialization methods in. net:
Binary serialization
XML serialization
SOAP serialization
Binary serialization
Binary serialization refers to the binary format after Object serialization. Binary Serialization is implemented through the BinaryFormatter class, which is located under the namespace System. Runtime. Serialization. Formatters. Binary.
XML serialization
XML serialization means that the object serialized results are in XML format. Saving XML Serialization is implemented through the XmlSerializer class, which is located in the namespace of System. Xml. Serialization.
SOAP serialization
The so-called SOAP serialization means that the object serialized results comply with the SOAP protocol, that is, they can be transmitted through the SOAP protocol (do not know the SOAP protocol? Baidu ). SOAP serialization is implemented through the SoapFormatter class, which is located in System. runtime. serialization. formatters. in the Soap namespace, you must manually add references to the namespace, as shown in:
The following code writes a class for serialization and deserialization. The code of this class is as follows:
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace MySerializeDemo
{
[Serializable]
/// <Summary>
/// Object to be serialized
/// By Zhou Gong
/// Compilation Time:
/// </Summary>
Public class MyObject
{
// [NonSerialized]
Private string name;
Private DateTime birthday;
Private string homePlace;
/// <Summary>
/// Place of Birth
/// </Summary>
Public string HomePlace
{
Get {return homePlace ;}
Set {homePlace = value ;}
}
/// <Summary>
/// Birthday
/// </Summary>
Public DateTime Birthday
{
Get {return birthday ;}
Set {birthday = value ;}
}
/// <Summary>
/// Name
/// </Summary>
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
/// <Summary>
/// Age
/// </Summary>
Public int Age
{
Get {return DateTime. Now. Year-birthday. Year ;}
}
/// <Summary>
/// Override the ToString () method
/// </Summary>
/// <Returns> </returns>
Public override string ToString ()
{
Return string. Format ("name: {0}, birthday: {1}, Birthplace: {2}, Age: {3}", name, birthday, homePlace, Age );
}
}
}
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace MySerializeDemo
{
[Serializable]
/// <Summary>
/// Object to be serialized
/// By Zhou Gong
/// Compilation Time:
/// </Summary>
Public class MyObject
{
// [NonSerialized]
Private string name;
Private DateTime birthday;
Private string homePlace;
/// <Summary>
/// Place of Birth
/// </Summary>
Public string HomePlace
{
Get {return homePlace ;}
Set {homePlace = value ;}
}
/// <Summary>
/// Birthday
/// </Summary>
Public DateTime Birthday
{
Get {return birthday ;}
Set {birthday = value ;}
}
/// <Summary>
/// Name
/// </Summary>
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
/// <Summary>
/// Age
/// </Summary>
Public int Age
{
Get {return DateTime. Now. Year-birthday. Year ;}
}
/// <Summary>
/// Override the ToString () method
/// </Summary>
/// <Returns> </returns>
Public override string ToString ()
{
Return string. Format ("name: {0}, birthday: {1}, Birthplace: {2}, Age: {3}", name, birthday, homePlace, Age );
}
}
}
The following code uses the above three classes for serialization and deserialization:
View plaincopy to clipboardprint?
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using System. Runtime. Serialization. Formatters;
Using System. Runtime. Serialization. Formatters. Binary;
Using System. Runtime. Serialization. Formatters. Soap;
Using System. Xml. Serialization;
Namespace MySerializeDemo
{
Class Program
{
Static void Main (string [] args)
{
MyObject obj = new MyObject ();
Obj. Birthday = new DateTime (1979, 11, 7 );
Obj. HomePlace = "Hubei ";
Obj. Name = "Zhou Gong ";
Console. WriteLine ("========= use the BinaryFormatter class for serialization and deserialization. ==== ");
BinarySerialize (obj );
BinaryDeserialize ("C: \ MyObject. dat ");
Console. WriteLine ("========= use the SoapFormatter class for serialization and deserialization. ==== ");
SOAPSerialize (obj );
SOAPDeserialize ("C: \ MyObject. soap ");
Console. WriteLine ("========= use the XmlSerializer class for serialization and deserialization. ==== ");
XMLSerialize (obj );
XMLDeserialize ("C: \ MyObject. xml ");
}
/// <Summary>
/// Binary serialized object
/// </Summary>
/// <Param name = "obj"> </param>
Public static void BinarySerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. dat", FileMode. Create, FileAccess. Write ))
{
BinaryFormatter formater = new BinaryFormatter ();
Formater. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void BinaryDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
BinaryFormatter formater = new BinaryFormatter ();
MyObject obj = (MyObject) formater. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary serialized object
/// </Summary>
/// <Param name = "obj"> </param>
Public static void SOAPSerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. soap", FileMode. Create, FileAccess. Write ))
{
SoapFormatter formater = new SoapFormatter ();
Formater. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void SOAPDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
SoapFormatter formater = new SoapFormatter ();
MyObject obj = (MyObject) formater. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// XML serialization
/// </Summary>
/// <Param name = "obj"> </param>
Public static void XMLSerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. xml", FileMode. Create, FileAccess. Write ))
{
XmlSerializer serializer = new XmlSerializer (typeof (MyObject ));
Serializer. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// XML deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void XMLDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
XmlSerializer serializer = new XmlSerializer (typeof (MyObject ));
MyObject obj = (MyObject) serializer. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
}
}
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using System. Runtime. Serialization. Formatters;
Using System. Runtime. Serialization. Formatters. Binary;
Using System. Runtime. Serialization. Formatters. Soap;
Using System. Xml. Serialization;
Namespace MySerializeDemo
{
Class Program
{
Static void Main (string [] args)
{
MyObject obj = new MyObject ();
Obj. Birthday = new DateTime (1979, 11, 7 );
Obj. HomePlace = "Hubei ";
Obj. Name = "Zhou Gong ";
Console. WriteLine ("========= use the BinaryFormatter class for serialization and deserialization. ==== ");
BinarySerialize (obj );
BinaryDeserialize ("C: \ MyObject. dat ");
Console. WriteLine ("========= use the SoapFormatter class for serialization and deserialization. ==== ");
SOAPSerialize (obj );
SOAPDeserialize ("C: \ MyObject. soap ");
Console. WriteLine ("========= use the XmlSerializer class for serialization and deserialization. ==== ");
XMLSerialize (obj );
XMLDeserialize ("C: \ MyObject. xml ");
}
/// <Summary>
/// Binary serialized object
/// </Summary>
/// <Param name = "obj"> </param>
Public static void BinarySerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. dat", FileMode. Create, FileAccess. Write ))
{
BinaryFormatter formater = new BinaryFormatter ();
Formater. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void BinaryDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
BinaryFormatter formater = new BinaryFormatter ();
MyObject obj = (MyObject) formater. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary serialized object
/// </Summary>
/// <Param name = "obj"> </param>
Public static void SOAPSerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. soap", FileMode. Create, FileAccess. Write ))
{
SoapFormatter formater = new SoapFormatter ();
Formater. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// Binary deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void SOAPDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
SoapFormatter formater = new SoapFormatter ();
MyObject obj = (MyObject) formater. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// XML serialization
/// </Summary>
/// <Param name = "obj"> </param>
Public static void XMLSerialize (MyObject obj)
{
Using (FileStream stream = new FileStream ("C: \ MyObject. xml", FileMode. Create, FileAccess. Write ))
{
XmlSerializer serializer = new XmlSerializer (typeof (MyObject ));
Serializer. Serialize (stream, obj );
Console. WriteLine ("the object has been serialized. "+ Obj. ToString ());
}
}
/// <Summary>
/// XML deserialization
/// </Summary>
/// <Param name = "fileName"> </param>
Public static void XMLDeserialize (string fileName)
{
Using (FileStream stream = new FileStream (fileName, FileMode. Open, FileAccess. Read ))
{
XmlSerializer serializer = new XmlSerializer (typeof (MyObject ));
MyObject obj = (MyObject) serializer. Deserialize (stream );
Console. WriteLine ("the object has been deserialized. "+ Obj. ToString ());
}
}
}
}
The running effect of this program is as follows:
It can be seen that the above three classes can be used to serialize and save objects, and all of them can be deserialized and restored to the State before the object is serialized (this is exactly the meaning of serialization, can Save the running status of the object and restore it ). If you run the above Code, three files will be created under the root directory of the C drive, namely MyObject. dat, MyObject. soap and MyObject. xml file, because MyObject. dat is a binary file, so you cannot view the file content, but you can open MyObject. soap and MyObject. xml files to compare the differences.
Although the suffix of the MyObject. soap file is. soap, it can still be opened in Notepad. The following is the content of the MyObject. soap file:
View plaincopy to clipboardprint?
<SOAP-ENV: Envelope xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" xmlns: SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding/" xmlns: SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: clr = "http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV: encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/">
SOAP-ENV: Body>
<A1: MyObject id = "ref-1" xmlns: a1 = "http://schemas.microsoft.com/clr/nsassem/MySerializeDemo/MySerializeDemo,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null">
<Name id = "ref-3"> Zhou Gong </name>
<Birthday> 1979-11-07T00: 00: 00.0000000 + 08: 00 </birthday>
<HomePlace id = "ref-4"> Hubei </A1: MyObject>
SOAP-ENV: Body>
SOAP-ENV: Envelope>
<SOAP-ENV: Envelope xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" xmlns: SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding/" xmlns: SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: clr = "http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV: encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/">
SOAP-ENV: Body>
<A1: MyObject id = "ref-1" xmlns: a1 = "http://schemas.microsoft.com/clr/nsassem/MySerializeDemo/MySerializeDemo,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null">
<Name id = "ref-3"> Zhou Gong </name>
<Birthday> 1979-11-07T00: 00: 00.0000000 + 08: 00 </birthday>
<HomePlace id = "ref-4"> Hubei </A1: MyObject>
SOAP-ENV: Body>
SOAP-ENV: Envelope>
The MyObject. xml file can also be opened in Notepad. Its content is as follows:
View plaincopy to clipboardprint?
<? Xml version = "1.0"?>
<MyObject xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<HomePlace> Hubei </HomePlace>
<Birthday> 1979-11-07T00: 00: 00 </Birthday>
<Name> Zhou Gong </Name>
</MyObject>
<? Xml version = "1.0"?>
<MyObject xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<HomePlace> Hubei </HomePlace>
<Birthday> 1979-11-07T00: 00: 00 </Birthday>
<Name> Zhou Gong </Name>
</MyObject>
A friend familiar with the SOAP protocol can see that the content of the MyObject. soap file complies with the SOAP protocol. The MyObject. xml file is undoubtedly a file compliant with the XML specification.
The code is described as follows:
1. If BinaryFormatter class or SoapFormatter class is used for serialization, you must add the Serializable attribute to the class, as shown in the Code:
View plaincopy to clipboardprint?
[Serializable]
/// <Summary>
/// Object to be serialized
/// By Zhou Gong
/// Compilation Time:
/// </Summary>
Public class MyObject
[Serializable]
/// <Summary>
/// Object to be serialized
/// By Zhou Gong
/// Compilation Time:
/// </Summary>
Public class MyObject
If this attribute is not added to the object to be serialized, an exception is reported when the BinaryFormatter class or SoapFormatter class is used for serialization. However, this attribute is not required when the XmlSerializer class is used to serialize the object.
2. If you do not want to serialize a field, you can add the NonSerialized attribute to it so that the value of this field will not be saved during serialization. For example, you do not want to serialize the name field, you can write the following code:
View plaincopy to clipboardprint?
... // Other code
// [NonSerialized]
Private string name;
... // Other code
... // Other code
// [NonSerialized]
Private string name;
... // Other code
Running the program again will achieve the following results:
There is a yellow bottom line. Because the name field is not serialized, the original value is not obtained after binary serialization and SOAP serialization.
3. Note that the SoapFormatter class is out of date at the beginning of. net3.5. Microsoft recommends using the BinaryFormatter class for serialization and deserialization.
Zhou Gong
This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/zhoufoxcn/archive/2009/03/11/3978874.aspx