. Net c # serialization and deserialization

Source: Internet
Author: User
Tags custom name

The so-called serialization is the process of converting an object to a format that is easy to transmit. In general, the object is converted into a stream file and put into memory or IO files. For example, you can serialize an object and Use HTTP to transmit the object between the client and server over the Internet, or share the object with other applications. Conversely, deserialization reconstructs an object based on the stream.

. NET comes with two methods to serialize objects: Xml and binary. XML serialization does not convert methods, indexers, private fields, or read-only attributes (except for read-only sets ). To serialize all fields and attributes of an object (public and private), use BinaryFormatter instead of XML serialization (see ms-help: // MS. NETFramework. v20.chs/dv_fxserialization/html/8c63200d-db63-4a03-a93d-21641623df62.htmXML and SOAP serialization ).
The Processing Methods of the two programs are basically the same, both of which are based on the factory mode. Below I will only talk about the binary serialization method:
For example, we have an object: [Serializable] public class ClassToSerialize {
Public int id = 100;
Public string name = "Name ";
}

To serialize this object, you must add the Serializable attribute to the class, and then create a stream to be serialized and written: FileStream fileStream = new FileStream ("temp. dat ", FileMode. create); then Create the binary formatter: BinaryFormatter B = new BinaryFormatter (); then serialize: B. serialize (fileStream, c);, and then close the Save stream. (See the example below)

When reading a serialized object: The operation is the same, but FileStream fileStream = new FileStream ("temp. dat", FileMode. Open, FileAccess. Read, FileShare. Read );
ClassToSerialize c = (ClassToSerialize) B. Deserialize (fileStream );
Then you can read it. The complete example is: using System;
Using System. IO;
Using System. Runtime. Serialization;
Using System. Runtime. Serialization. Formatters. Binary;
Public class SerialTest {
Public void SerializeNow (){
ClassToSerialize c = new ClassToSerialize ();
FileStream fileStream = new FileStream ("temp. dat", FileMode. Create );
BinaryFormatter B = new BinaryFormatter ();
B. Serialize (fileStream, c );
FileStream. Close ();
}
Public void DeSerializeNow (){
ClassToSerialize c = new ClassToSerialize ();
FileStream fileStream = new FileStream ("temp. dat", FileMode. Open, FileAccess. Read, FileShare. Read );
BinaryFormatter B = new BinaryFormatter (); // SoapFormatter
C = (ClassToSerialize) B. Deserialize (fileStream );
Console. WriteLine (c. name );
FileStream. Close ();
}
Public static void Main (string [] s ){
SerialTest st = new SerialTest ();
St. SerializeNow ();
St. DeSerializeNow ();
}
}
[Serializable]
Public class ClassToSerialize {
Public int id = 100;
Public string name = "Name ";
}
This is the built-in serialization and deserialization operations. However, in many cases, an object is large and many private attributes and methods are not required, for example, serialization in the prototype mode only requires the sequential Clone method and some attributes. Private methods are not required. For example, when reading large-scale IO, read operations are not required at all... at this time, you need to integrate the ISerializable interface of the rewrite sequence:

You need to pay attention to the implementation of this interface. One is the constructor, mainly for the purpose of deserialization, and the other is GetObjectData, mainly for the execution of serialization, for example, we now have an Employee class that needs to serialize [Serializable ()] // Set this attribute to all the classes that want to serialize
Public class Employee: ISerializable // derive your class from ISerializable {
Public int EmpId;
Public string EmpName;
[NonSerialized ()]
Public string NoSerialString = "NoSerialString-Test ";
}
Note that [NonSerialized ()] exists before the NoSerialString attribute, which means that this attribute is not serialized by default, but the default value is used.
The first is the constructor: public Employee (SerializationInfo info, StreamingContext ctxt)
{
EmpId = (int) info. GetValue ("EmployeeId", typeof (int ));
EmpName = (String) info. GetValue ("EmployeeName", typeof (string ));
// NoSerialString = (String) info. GetValue ("NoSerialString", typeof (string ));
}

Then there is the serialization method, which is how to save the data when writing the stream:
Public void GetObjectData (SerializationInfo info, StreamingContext ctxt)
{
// You can use any custom name for your name-value pair. But make sure you
// Read the values with the same name. For ex:-If you write EmpId as "EmployeeId"
// Then you shoshould read the same with "EmployeeId"
Info. AddValue ("EmployeeId", EmpId );
Info. AddValue ("EmployeeName", EmpName );
}

Write the above two methods into the Employee class, and then write a test program:
Public class ObjSerial {
Public static void Main (String [] args ){
Employee mp = new Employee ();
Mp. EmpId = 10;
Mp. EmpName = "Omkumar ";
Mp. NoSerialString = "hello ";

// Serialization
Stream stream = File. Open ("EmployeeInfo. osl", FileMode. Create );
BinaryFormatter bformatter = new BinaryFormatter ();

Console. WriteLine ("Writing Employee Information ");
Bformatter. Serialize (stream, mp );
Stream. Close ();
 

Mp = null;
// Reverse Sequence
Stream = File. Open ("EmployeeInfo. osl", FileMode. Open );
Bformatter = new BinaryFormatter ();

Console. WriteLine ("Reading Employee Information ");
Mp = (Employee) bformatter. Deserialize (stream );
Stream. Close ();

Console. WriteLine ("Employee Id: {0}", mp. EmpId. ToString ());
Console. WriteLine ("Employee Name: {0}", mp. EmpName );
Console. WriteLine ("Maid: {0}", mp. NoSerialString );
}
}

The execution result is: Writing Employee Information.
Reading Employee Information
Employee Id: 10
Employee Name: Omkumar
Employee NoSerialString: NoSerialString-Test

We can see that the value of the Employee NoSerialString property does not exist. It retains the default value and is not serialized.

Author: "Computer Encyclopedia (only used for technology .."

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.