In-depth understanding of C # serialization and deserialization

Source: Internet
Author: User

Before exploring C # serialization and deserialization in depth, we must first understand what serialization is, also known as serialization, is.. NET runtime environment is used to support user-defined streaming mechanisms. Serialization is to save an object to a file or database field. deserialization is to convert the file to the original object when appropriate. The objective is to make the custom object persistent by storage, or to transmit the object from one place to another .. The NET Framework provides two serializing methods:
1. Use BinaryFormatter for serialization;
2. Use SoapFormatter for serialization;
3. Use XmlSerializer for serialization.
The first method provides a simple binary data stream and some additional types of information, while the second method formats the data stream for XML storage. The third method is similar to the second method in XML format storage, it is much simpler than the second XML format (removes the extra information unique to SOAP ). You can use the [Serializable] attribute to serialize a class. If the elements of a class do not want to be serialized, 1 and 2 can use the [NonSerialized] attribute for flag. 2. You can use the [XmlIgnore] flag.
Next let's get to know more about C # serialization and deserialization:
C # serialization and deserialization 1. Use BinaryFormatter for serialization
The following is a serializable class: Copy codeThe Code is as follows: using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. IO;
Using System. Runtime. Serialization. Formatters. Binary;
/** // <Summary>
/// Summary of ClassToSerialize
/// </Summary>
[Serializable]
Public class ClassToSerialize
{
Public int id = 100;
Public string name = "Name ";
[NonSerialized]
Public string Sex = "male ";
}

The following describes the serialization and deserialization methods:Copy codeThe Code is as follows: public void SerializeNow ()
{
ClassToSerialize c = new ClassToSerialize ();
FileStream fileStream =
New FileStream ("c: \ temp. dat", FileMode. Create );
BinaryFormatter B = new BinaryFormatter ();
B. Serialize (fileStream, c );
FileStream. Close ();
}
Public void DeSerializeNow ()
{
ClassToSerialize c = new ClassToSerialize ();
C. Sex = "kkkk ";
FileStream fileStream =
New FileStream ("c: \ temp. dat ",
FileMode. Open, FileAccess. Read, FileShare. Read );
BinaryFormatter B = new BinaryFormatter ();
C = B. Deserialize (fileStream) as ClassToSerialize;
Response. Write (c. name );
Response. Write (c. Sex );
FileStream. Close ();
}

Call the above two methods to see the serialized result: the Sex property is always null because it is marked as [NonSerialized.
C # serialization and deserialization 2. Use SoapFormatter for serialization
Similar to BinaryFormatter, you only need to make a simple modification:
A. Change. Formatter. Binary in the using statement to. Formatter. Soap;
B. replace all BinaryFormatter with SoapFormatter.
C. Make sure that the file name is. xml.
After the above simple changes, SoapFormatter can be serialized. The generated file is an xml file.
C # serialization and deserialization 3. Use XmlSerializer for serialization
There is another question about the formatter. Suppose we need XML, but we do not want additional information unique to SOAP. What should we do? There are two solutions: either compile a class that implements the IFormatter interface, using a method similar to the SoapFormatter class, but there is no information you don't need; or use the library class XmlSerializer, this class does not use the Serializable attribute, but it provides similar functions.
If we don't want to use the mainstream serialization mechanism, but want to use XmlSeralizer for serialization, we need to modify it as follows:
A. Add the System. Xml. Serialization namespace.
B. the Serializable and NoSerialized attributes are ignored, but the XmlIgnore attributes are used. Their behavior is similar to that of NoSerialized.
C. XmlSeralizer requires the class to have a default constructor. This condition may already be met.
The following is an example of C # serialization and deserialization:
Class to be serialized:Copy codeThe Code is as follows: using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Xml. Serialization;

Copy codeThe Code is as follows:

[Serializable]
Public class Person
{
Private string name;
Public string Name
{
Get
{
<SPAN style = "WHITE-SPACE: pre"> </SPAN> return name;
<SPAN style = "WHITE-SPACE: pre"> </SPAN>}
<SPAN style = "WHITE-SPACE: pre"> </SPAN> set
<SPAN style = "WHITE-SPACE: pre"> </SPAN> {
<SPAN style = "WHITE-SPACE: pre"> </SPAN> name = value;
<SPAN style = "WHITE-SPACE: pre"> </SPAN>}
}

Public string Sex;
Public int Age = 31;
Public Course [] Courses;

Public Person ()
{
}
Public Person (string Name)
{
<SPAN style = "WHITE-SPACE: pre"> </SPAN> name = Name;
<SPAN style = "WHITE-SPACE: pre"> </SPAN> Sex = "male ";
}
}

Copy codeThe Code is as follows: [Serializable]
Public class Course
{
Public string Name;
[XmlIgnore]
Public string Description;
Public Course ()
{
}
Public Course (string name, string description)
{
<SPAN style = "WHITE-SPACE: pre"> </SPAN> Name = name;
<SPAN style = "WHITE-SPACE: pre"> </SPAN> Description = description;
}
}

C # serialization and deserialization methods:Copy codeThe Code is as follows: public void XMLSerialize ()
{
Person c = new Person ("cyj ");
C. Courses = new Course [2];
C. Courses [0] = new Course ("English", "communication tools ");
C. Courses [1] = new Course ("Mathematics", "Natural Science ");
XmlSerializer xs = new XmlSerializer (typeof (Person ));
Stream stream = new FileStream ("c: \ cyj. XML", FileMode. Create, FileAccess. Write, FileShare. Read );
Xs. Serialize (stream, c );
Stream. Close ();
}
Public void XMLDeserialize ()
{
XmlSerializer xs = new XmlSerializer (typeof (Person ));
Stream stream = new FileStream ("C: \ cyj. XML", FileMode. Open, FileAccess. Read, FileShare. Read );
Person p = xs. Deserialize (stream) as Person;
Response. Write (p. Name );
Response. Write (p. Age. ToString ());
Response. Write (p. Courses [0]. Name );
Response. Write (p. Courses [0]. Description );
Response. Write (p. Courses [1]. Name );
Response. Write (p. Courses [1]. Description );
Stream. Close ();
}

Here, the Description attribute value of the Course class is always null, and this node is not found in the generated xml document, as shown below:Copy codeThe Code is as follows: <? Xml version = "1.0 "? >
<Person xmlns: xsi =
Http://www.w3.org/2001/XMLSchema-instance"
Xmlns: xsd = "http://www.w3.org/2001/XMLSchema">
<Sex> male </Sex>
<Age> 31 </Age>
<Courses>
<Course>
<Name> English </Name>
<Description> communication tool </Description>
</Course>
<Course>
<Name> mathematics </Name>
<Description> natural science </Description>
</Course>
</Courses>
<Name> cyj </Name>
</Person>

C # serialization and deserialization 4. Custom serialization
If you want to serialize the class but are not satisfied with the data stream organization method, you can customize the serialization behavior by implementing interfaces in the Custom class. This interface has only one method, GetObjectData. This method is used to fill in the data required for serializing class objects into the SerializationInfo object. The formatter you use will construct the SerializationInfo object, and then call GetObjectData during serialization. If the parent class of the class also implements ISerializable, you should call the parent class implementation of GetObjectData. If you implement ISerializable, you must also provide a constructor with a specific prototype. The parameter list of this constructor must be the same as that of GetObjectData. This constructor should be declared private or protected to prevent careless developers from using it directly. Example:
C # serialization and deserialization:
Copy codeThe Code is as follows: using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Runtime. Serialization;
Using System. Runtime. Serialization. Formatters. Binary;
/** // <Summary>
/// Abstract description of Employee
/// </Summary>
[Serializable]
Public class Employee: ISerializable
{
Public int EmpId = 100;
Public string EmpName = "Andy Lau ";
[NonSerialized]
Public string NoSerialString = "NoSerialString-Test ";
Public Employee ()
{
//
<SPAN style = "WHITE-SPACE: pre"> </SPAN> // TODO: add the constructor logic here.
<SPAN style = "WHITE-SPACE: pre"> </SPAN> //
}
Private Employee (SerializationInfo info, StreamingContext ctxt)
{
<SPAN style = "WHITE-SPACE: pre"> </SPAN> EmpId = (int) info. GetValue ("EmployeeId", typeof (int ));
<SPAN style = "WHITE-SPACE: pre"> </SPAN> EmpName = (String) info. GetValue ("EmployeeName", typeof (string ));
<SPAN style = "WHITE-SPACE: pre"> </SPAN> // NoSerialString = (String) info. GetValue ("EmployeeString", typeof (string ));
}
Public void GetObjectData (SerializationInfo info, StreamingContext ctxt)
{
<SPAN style = "WHITE-SPACE: pre"> </SPAN> info. AddValue ("EmployeeId", EmpId );
<SPAN style = "WHITE-SPACE: pre"> </SPAN> info. AddValue ("EmployeeName", EmpName );
<SPAN style = "WHITE-SPACE: pre"> </SPAN> // info. AddValue ("EmployeeString", NoSerialString );
}
}

C # serialization and deserialization methods:Copy codeThe Code is as follows: public void OtherEmployeeClassTest ()
{
Employee mp = new Employee ();
Mp. EmpId = 10;
Mp. EmpName = "Qiu Feng ";
Mp. NoSerialString = "hello ";
Stream steam = File. Open ("c: \ temp3.dat", FileMode. Create );
BinaryFormatter bf = new BinaryFormatter ();
Response. Write ("Writing Employee Info :");
Bf. Serialize (steam, mp );
Steam. Close ();
Mp = null;
// C # deserialization and deserialization
Stream steam2 = File. Open ("c: \ temp3.dat", FileMode. Open );
BinaryFormatter bf2 = new BinaryFormatter ();
Response. Write ("Reading Employee Info :");
Employee mp2 = (Employee) bf2.Deserialize (steam2 );
Steam2.Close ();
Response. Write (mp2.EmpId );
Response. Write (mp2.EmpName );
Response. Write (mp2.NoSerialString );
}

The in-depth discussion of C # serialization and deserialization is a process of experience and experimentation. I hope this article will help you understand and learn C # serialization and deserialization.

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.