[. Net Object-Oriented programming advanced] (9) Serialization (1) binary stream Serialization and binary Serialization
[. Net Object-Oriented programming advanced] (9) Serialization (Serialization) (1) binary stream Serialization
This section introduces:
In. NET programming, it is often necessary to convert the object to another format for transmission or storage after the object is processed. This process of turning the object to another data format is Serialization ).
The opposite process is Deserialization ). Mastering and making good use of the serialization and deserialization methods is of great benefit to improving programming-oriented technologies.
Before reading:
A. Example of classes and classes [. net idea Object-Oriented Programming Basics] example (9) Examples of classes and Classes
B. Member of the class [. net pipeline Object-Oriented Programming Basics] member of the pipeline (10) Member of the pipeline class (field, attribute, method)
1. What is serialization and deserialization?
Serialization: Serialization refers to the process of converting the object state to a format that can be maintained or transmitted.
Deserialization: the opposite to serialization is Deserialization, which switches the stream to an object.These two processes can be combined to easily store and transmit data.
The process of storing or recovering objects in MFC is Serialization, also known as Persistent (perpetual survival ). During serialization, the object writes its current state to a temporary or permanent storage area (stored in a file ). Later, you can re-create the object by reading or deserializing the object status from the bucket. In order to achieve sustainable survival in the object-oriented model.
2. serialization Technology in. NET
. NET Framework serialization technology, mainly including the following:
Strictly speaking, there are only two types: binary serialization and Data Format protocol serialization (including XML and SOAP. JSON)
A. Binary (Stream) serialization (BinaryFormatter)
-->(Dominated by C/S)
Binary serialization maintains type fidelity, which is used to reserve the object state between different calls of an application.
For example, objects can be shared between different applications by serializing objects to the clipboard. You can serialize an object to a stream, disk, memory, or network. Remote Processing uses serialized "pass through value" to pass objects between computer or application domains.
B. XML serialization (XmlSerializer) --> (B/S C/S General)
XML serialization only serializes public attributes and fields, and does not maintain type fidelity. It is useful for applications that provide or use data without limiting the use of the data. Because XML is an open standard, it is a good choice for sharing data through the Web.
C. SOAP serialization (SoapFormatter) --> (common, mainly used for data exchange by WebSerice)
SOAP is also an open standard. This SOAP protocol is an ideal choice for information interaction between heterogeneous applications.
D. DataContractSerializer --> (B/S direction, mainly used for WCF Communication)
F. Json serialization (DataContractJsonSerializer) --> (B/S mobile development direction)
Json (JavaScript Object Notation) is a lightweight data exchange method.
3. Binary (Stream) serialization
This section describes binary (Stream) serialization.
Binary (Stream) serialization is mainly used in underlying (relative) communication. We know that computers transmit and store data to media (hard disks, etc.) through binary ), in object-oriented programming, how to accurately and quickly convert an object instance to a binary stream is what we will introduce in this section.
Object = binary stream: binary stream serialization
Next, I will use the "martial arts master" Class in the "Basic article" to create files through "file stream.
First, create the data class and serialization method as follows:
Note: [Serializable] identifier
The Serializable attribute explicitly indicates that the class can be serialized.
Similarly, we can use the NonSerializable attribute to explicitly indicate that the class cannot be serialized.
/// <Summary> /// class: martial arts experts /// MartialArtsMaster /// </summary> [Serializable] class MartialArtsMaster {// <summary> /// No. /// </summary> public int Id {get; set ;}//< summary> /// Name /// </summary> public string Name {get; set ;} /// <summary> /// Age /// </summary> public int Age {get; set ;} /// <summary> /// martial // </summary> public string Menpai {get; set ;} /// <summary> /// Wuxue /// </summary> Public string Kungfu {get; set ;}/// <summary >/// Level /// </summary> public int Level {get; set ;}} /// <summary> /// binary serialization and deserialization class /// </summary> public class Serializer {/// <summary> /// use a binary serialization object. /// </Summary> /// <param name = "value"> </param> /// <returns> </returns> public static byte [] SerializeBytes (object value) {if (value = null) return null; var stream = new MemoryStream (); new BinaryFormatter (). serialize (stream, value); // var dto = Encoding. UTF8.GetString (stream. getBuffer (); var bytes = stream. toArray (); return bytes;} // <summary> // use a binary deserialization object. /// </Summary> /// <param name = "bytes"> </param> /// <returns> </returns> public static object DeserializeBytes (byte [] bytes) {if (bytes = null) return null; // var bytes = Encoding. UTF8.GetBytes (dto as string); var stream = new MemoryStream (bytes); var result = new BinaryFormatter (). deserialize (stream); return result ;}}
The following is the call method:
// Namespace in this example // using System. runtime. serialization. formatters. binary; // using System. IO; // initialize martial arts master var master = new List <MartialArtsMaster> () {new MartialArtsMaster () {Id = 1, Name = "Huang Rong", Age = 18, menpai = "", Kungfu = "", Level = 9}, new MartialArtsMaster () {Id = 2, Name = "", Age = 70, menpai = "", Kungfu = "", Level = 10}, new MartialArtsMaster () {Id = 3, Name = "Guo Jing", Age = 22, menpai = "", Kungfu = "", Level = 10}, new MartialArtsMaster () {Id = 4, Name = "", Age = 50, menpai = "Mingjiao", Kungfu = "", Level = 1}, new MartialArtsMaster () {Id = 5, Name = "", Age = 35, menpai = "Mingjiao", Kungfu = "", Level = 10}, new MartialArtsMaster () {Id = 6, Name = "Lin pingzhi", Age = 23, menpai = "Huashan", Kungfu = "", Level = 7}, new MartialArtsMaster () {Id = 7, Name = "Yue Bu", Age = 50, menpai = "Huashan", Kungfu = "", Level = 8 }}; // Write File streams to using (FileStream fs = new FileStream (@ "F: \ 360 synchronize cloud disk \ 360 synchronize cloud disk \ blog \ serialization \ master. obj ", FileMode. append) {var myByte = Serializer. serializeBytes (master); fs. write (myByte, 0, myByte. length); fs. close () ;}; // file stream read using (FileStream fsRead = new FileStream (@ "F: \ 360 sync cloud disk \ 360 sync cloud disk \ blog \ serialization \ master. obj ", FileMode. open) {int fsLen = (int) fsRead. length; byte [] heByte = new byte [fsLen]; int r = fsRead. read (heByte, 0, heByte. length); var myObj = Serializer. deserializeBytes (heByte) as List <MartialArtsMaster>; Console. writeLine ("No. --- name --- age --- school --- martial arts --- Grade"); myObj. forEach (m => Console. writeLine (m. id + "---" + m. name + "---" + m. age + "---" + m. menpai + "---" + m. kungfu + "---" + m. level ));}
The running result is as follows:
First, the created file master. obj:
Read the running result as follows:
4. Key points:
A. Understanding of serialization and deserialization:
Serialization: Serialization refers to the process of converting the object state to a format that can be maintained or transmitted.
Deserialization: the opposite to serialization is Deserialization, which switches the stream to an object.
B. serialization Technology in. NET
The main usage direction is specified to facilitate the learning of friends.
(1) binary (Stream) serialization (BinaryFormatter) --> (dominated by C/S)
(2) XML serialization (XmlSerializer) --> (B/S C/S General)
(3) SOAP serialization (SoapFormatter --> (common, mainly used for data exchange by WebSerice)
(4) DataContractSerializer --> (B/S direction, mainly used for WCF Communication)
(5) Json serialization (DataContractJsonSerializer) --> (B/S mobile development direction)
========================================================== ========================================================== ====================
Returned directory
<If it is helpful to you, please click here for recommendations. If yesDo not understand or make a mistakePoints, Please exchange more>
<If you have any difficulty reading this series of articles, please read. net Object-Oriented Programming basics first>
<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>
. NET exchange group: 467189533
========================================================== ========================================================== ====================