Serialization is the process of converting an object's state to a format that can be persisted or transmitted. The opposite of serialization is deserialization, which converts a stream to an object. These two processes combine to make it easy to store and transfer data.
Several serialization techniques:
1 binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share objects between different applications by serializing the object to the Clipboard. You can serialize objects to streams, disks, memory, and networks, and so on. Remoting uses serialization "by value" to pass an object between a computer or an application domain.
2 XML serialization only serializes public properties and fields, and does not maintain type fidelity. This is useful when you want to provide or use data without restricting applications that use that data. Because XML is an open standard, this is a good choice for sharing data over the WEB. SOAP is also an open standard, making it an attractive option.
3 The type instance is serialized and deserialized into an XML stream or document (or JSON format) using the provided data contract. Often applies to WCF communications.
BinaryFormatter
Serialization can be defined as the process of storing the state of an object in a storage medium. In this procedure, both the public and private fields of the object and the name of the class, including the assembly that contains the class, are converted to a byte stream and then written to the data flow. When the object is deserialized later, an exact copy of the original object is created.
1, the simplest way to make a class serializable is to use the Serializable property tag as follows.
2. Selective serialization
By labeling member variables with the NonSerialized property, you can prevent them from being serialized
3, custom serialization
1 To run the custom method during and after serialization
Best practices are also the simplest approach (introduced in the. Net Framework version 2.0), which is to apply the following attributes to the method used to correct the data during and after serialization:
- Ondeserializedattribute
- Ondeserializingattribute
- Onserializedattribute
- Onserializingattribute
Specific examples are as follows:
This is the object of would be serialized and deserialized.
[Serializable ()] public class Testsimpleobject {//This ' is serialized ' and ' deserialized with no ' change.
public int member1;
The value of this field is set and reset during and//after serialization.
private string Member2; This field is not serialized.
The Ondeserializedattribute//is used to set the ' member value ' after serialization.
[NonSerialized ()] public string Member3;
This field was set to null, but populated after deserialization.
private string Member4;
Constructor for the class.
Public Testsimpleobject () {member1 = 11;
Member2 = "Hello world!";
Member3 = "This is a nonserialized value";
Member4 = null;
public void Print () {Console.WriteLine ("Member1 = ' {0} '", member1);
Console.WriteLine ("Member2 = ' {0} '", member2);
Console.WriteLine ("Member3 = ' {0} '", Member3);
Console.WriteLine ("Member4 = ' {0} '", member4); [OnSerializing ()] internal void Onserializingmethod (StreamingContext context) {member2 = ' This value went I
Nto the data file during serialization. ";} [OnSerialized ()] internal void Onserializedmethod (StreamingContext context) {member2 = ' This value is reset afte
R serialization. ";} [OnDeserializing ()] internal void Ondeserializingmethod (StreamingContext context) {Member3 = ' This value is set
During deserialization "; [OnDeserialized ()] internal void Ondeserializedmethod (StreamingContext context) {member4 = ' This value is s
ET after deserialization. ";}}
2) Implement ISerializable interface
Default serialization should not be used for classes that are marked with the Serializable property and have declarative or imperative security on the class level or on their constructors. Instead, these classes should always implement the ISerializable interface. Implementing ISerializable involves implementing GetObjectData methods and special constructors that are used when deserializing objects.
Specific examples are as follows:
[Serializable]
public class myobject:iserializable
{public
int n1;
public int n2;
Public String str;
Public MyObject ()
{
}
protected MyObject (SerializationInfo info, StreamingContext context)
{
N1 = info. GetInt32 ("i");
N2 = info. GetInt32 ("J");
str = info. GetString ("K");
}
[SecurityPermissionAttribute (Securityaction.demand,serializationformatter
=true)] public
virtual void GetObjectData (SerializationInfo info, StreamingContext context)
{
info. AddValue ("I", N1);
Info. AddValue ("J", N2);
Info. AddValue ("K", str);
}
Attention:
The constructor is not invoked when an object is deserialized. This constraint is imposed on deserialization for performance reasons. However, this violates some of the usual conventions between the runtime and the object writer, and developers should ensure that they understand the consequences of marking objects as serializable.
SoapFormatter
Serializes and deserializes the graphics of an object or an entire connection object in a SOAP format. The basic usage is similar to BinaryFormatter. The SoapFormatter and BinaryFormatter two classes implement the Iremotingformatter interface to support remote procedure call (RPC) to implement the IFormatter interface (by Iremotingformatter Inheritance) to support serialization of object graphics. The SoapFormatter class also supports RPC for Isoapmessage objects without using the Iremotingformatter feature.
XmlSerializer
Serializes an object into an XML document and deserializes an object from an XML document. XmlSerializer allows you to control how objects are encoded into XML.
XML serialization is the process of converting an object's public properties and fields into a sequential format, which refers to XML, for storage or transmission. Deserialization is the object that recreated the original state from the XML output. Therefore, serialization can be treated as a method of saving the state of an object to a stream or buffer. For example, ASP.net uses the XmlSerializer class to encode an XML WEB services message.
Example:
C # code
public class MyClass
{public
MyObject myobjectproperty;
}
public class MyObject
{public
string objectname;
}
After serialization of XML
<MyClass>
<MyObjectProperty>
<objectname>my string</objectname>
</ Myobjectproperty>
</MyClass>
You can also control the output of XML through markup
1, default value
DefaultValueAttribute
2. Filter a property or field
XmlIgnoreAttribute
3. Override default serialization logic
Specifically visible: Http://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlattributeoverrides (v=vs.80). aspx
Other control means, specifically visible http://msdn.microsoft.com/zh-cn/library/83y7df3e (v=vs.80). aspx
4. Serializing an object into a SOAP-encoded XML stream
Http://msdn.microsoft.com/zh-cn/library/bd04skah (v=vs.80). aspx
Attention
XML serialization does not convert methods, indexers, private fields, or read-only properties (except for read-only collections). To serialize all the fields and properties (public and private) of an object, use BinaryFormatter instead of XML serialization.
DataContractSerializer
Serializes and deserializes an instance of a type into an XML stream or document using the provided data contract. This class cannot be inherited.
DataContractSerializer is used to serialize and deserialize data sent in Windows communication Foundation (WCF) messages. You can specify the properties and fields to serialize by applying the DataContractAttribute attribute to the class and applying the DataMemberAttribute attribute to the class member.
Use steps:
1) DataContractSerializer is used in conjunction with DataContractAttribute and DataMemberAttribute classes.
To prepare for serialization of a class, apply DataContractAttribute to the class. For each member of the class that returns the data to be serialized, apply DataMemberAttribute. You can serialize fields and properties regardless of their accessibility level: private, protected, internal, protected internal, or public.
2) added to a collection of known types
When serializing or deserializing an object, DataContractSerializer must be "known" for that type. First, create a class instance that implements Ienumerable<t> (such as list<t>) and add a known type to the collection. Then, use the Accept ienumerable<t> (for example, [M:system.runtime.serialization.datacontractserializer. #ctor (System.Type, One of the overloads of System.collections.generic.ienumerable{system.type}] creates an instance of DataContractSerializer.
Concrete Examples:
Namespace Datacontractserializerexample {using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.Runtime.Serialization;
Using System.Xml; You are must apply a datacontractattribute or SerializableAttribute/to a class to have it serialized by the Datacontra
Ctserializer. [DataContract (Name = "Customer", Namespace = "http://www.contoso.com")] class Person:iextensibledataobject {[Da
Tamember ()] public string FirstName;
[DataMember] public string LastName;
[DataMember ()] public int ID;
Public person (string newfname, string newlname, int newID) {FirstName = Newfname;
LastName = Newlname;
ID = NewID;
Private Extensiondataobject Extensiondata_value;
Public Extensiondataobject ExtensionData {get {return extensiondata_value;
} set {extensiondata_value = Value; }} public sealed class Test {private Test () {} public static void Main () {try {writeobject ("Datacontractserializerexample.xml
");
ReadObject ("Datacontractserializerexample.xml");
catch (SerializationException Serexc) {Console.WriteLine ("Serialization Failed");
Console.WriteLine (Serexc.message); catch (Exception exc) {Console.WriteLine ("The serialization operation: {0} failed CE: {1} ", exc. Message, exc.
StackTrace);
Finally {Console.WriteLine ("Press <Enter> to exit ...");
Console.ReadLine (); public static void WriteObject (String fileName) {Console.WriteLine (' Creating a person obj
ECT and serializing it. ");
person P1 = new Person ("Zighetti", "Barbara", 101);
FileStream writer = new FileStream (FileName, FileMode.Create); DataContractSerializer ser = new DataContractSerializer (typeof (Person)); Ser.
WriteObject (writer, p1); Writer.
Close (); public static void ReadObject (String fileName) {Console.WriteLine ("Deserializing a instance of the Obje
Ct. ");
FileStream fs = new FileStream (FileName, FileMode.Open);
XmlDictionaryReader reader = Xmldictionaryreader.createtextreader (FS, New XmlDictionaryReaderQuotas ());
DataContractSerializer ser = new DataContractSerializer (typeof (person));
Deserialize the data and read it from the instance. Person Deserializedperson = (person) ser.
ReadObject (reader, true); Reader.
Close (); Fs.
Close ();
Console.WriteLine (String.Format ("{0} {1}, ID: {2}", Deserializedperson.firstname, Deserializedperson.lastname,
Deserializedperson.id));
}
}
DataContractJsonSerializer
Serializes objects into JavaScript Object Notation (JSON) and deserializes the JSON data into objects. This class cannot be inherited.
The specific use is similar to DataContractSerializer. Don't repeat it here.
The following is a summary of the use of these methods, hoping to bring some help.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.IO;
Using System.Runtime.Serialization;
Using System.Runtime.Serialization.Json;
Using System.Runtime.Serialization.Formatters.Binary;
Using System.Runtime.Serialization.Formatters.Soap;
Using System.Xml.Serialization; namespace Serializersample {///<summary>///serialization Help class///</summary> public sealed class Serializehelp ER {#region datacontract serialization///<summary>///datacontract serialization///</summary>///<p Aram Name= "value" ></param>///<param name= "knowntypes" ></param>///<returns></retu rns> public static string Serializedatacontract (object value, list<type> knowntypes = null) {DATAC Ontractserializer DataContractSerializer = new DataContractSerializer (value.
GetType (), knowntypes); using (MemoryStream ms = new MemoryStream ()) {DATACONTRACTSERIALIZER.WRiteobject (MS, value); Ms.
Seek (0, seekorigin.begin); using (StreamReader sr = new StreamReader (ms)) {return Sr.
ReadToEnd (); }}///<summary>///datacontract deserialization///</summary>///<typeparam name= "T" &G t;</typeparam>///<param name= "xml" ></param>///<returns></returns> public STA Tic T deserializedatacontract<t> (string xml) {using (MemoryStream ms = new MemoryStream (Encoding.UTF8.Get
Bytes (XML)) {DataContractSerializer serializer = new DataContractSerializer (typeof (T)); Return (T) serializer.
ReadObject (MS); #endregion #region Datacontractjson serialization///<summary>///Datacontractjson serialization///</s ummary>///<param name= "value" ></param>///<returns></returns> public static Stri Ng Serializedatacontractjson (object value) {DATACONTRACTJSonserializer DataContractSerializer = new DataContractJsonSerializer (value.
GetType ());
using (MemoryStream ms = new MemoryStream ()) {Datacontractserializer.writeobject (MS, value); Return Encoding.UTF8.GetString (Ms.
ToArray ()); }///<summary>///Datacontractjson deserialization///</summary>///<param name= "type" >< ;/param>///<param name= "str" ></param>///<returns></returns> public static objec T Deserializedatacontractjson (type type, string str) {DataContractJsonSerializer DataContractSerializer = new D
Atacontractjsonserializer (type); using (MemoryStream ms = new MemoryStream (System.Text.Encoding.UTF8.GetBytes (str))) {return Datacontractser Ializer.
ReadObject (MS); }///<summary>///Datacontractjson deserialization///</summary>///<typeparam name= "T" >&L t;/typeparam>///<param name= "JSON" ></param>///<returns></returns> public T deserializedatacontractjson<t> (string json) {
DataContractJsonSerializer DataContractSerializer = new DataContractJsonSerializer (typeof (T)); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (JSON)) {return (T) DataContractSerializer.
ReadObject (MS); #endregion #region XmlSerializer serialization///<summary>///serializes objects into XML documents and deserializes objects from XML documents.
XmlSerializer allows you to control how objects are encoded into XML. </summary>///<param name= "value" ></param>///<returns></returns> public s Tatic string Serializexml (object value) {XmlSerializer serializer = new XmlSerializer (value.
GetType ()); using (MemoryStream ms = new MemoryStream ()) {serializer.
Serialize (MS, value); Ms.
Seek (0, seekorigin.begin); using (StreamReader sr = new StreamReader (ms)) {return Sr. ReadToEnd(); }}///<summary>///XmlSerializer deserialization///</summary>///<param name= "type" &G t;</param>///<param name= "str" ></param>///<returns></returns> public static
Object Deserializexml (Type type, string str) {XmlSerializer serializer = new XmlSerializer (type);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes (str); using (MemoryStream ms = new MemoryStream (bytes)) {return serializer.
Deserialize (MS); }} #endregion #region BinaryFormatter serialization///<summary>///BinaryFormatter serialization///must type must be marked For serializable///</summary>///<param name= "obj" ></param>///<returns></returns&
Gt
public static string Serializebinaryformatter (Object obj) {BinaryFormatter formatter = new BinaryFormatter (); using (MemoryStream ms = new MemoryStream ()) {formatter. Serialize (Ms,obj); byte[] bytes = Ms.
ToArray (); obj = formatter.
Deserialize (new MemoryStream (bytes)); If it is in UTF8 format, the error is deserialized.
You can use the Default format, however, it is a good idea to return Encoding.Default.GetString (bytes) with a reference to a byte array. }///<summary>///BinaryFormatter deserialization///must be marked as serializable///</summary>// /<param name= "Serializedstr" ></param>///<returns></returns> public static T deserialize
Binaryformatter<t> (String serializedstr) {BinaryFormatter formatter = new BinaryFormatter ();
byte[] bytes = Encoding.Default.GetBytes (SERIALIZEDSTR); using (MemoryStream ms = new MemoryStream (bytes)) {return (T) formatter.
Deserialize (MS); #endregion #region SoapFormatter serialization///<summary>///SoapFormatter serialization///the must type must be marked as SE Rializable///</summary>///<param name= "obj" ></param>///<returns></returns>
public static string Serializesoapformatter (Object obj) {SoapFormatter formatter = new SoapFormatter (); using (MemoryStream ms = new MemoryStream ()) {formatter.
Serialize (MS, obj); byte[] bytes = Ms.
ToArray ();
Return Encoding.UTF8.GetString (bytes); }///<summary>///SoapFormatter deserialization///must type must be marked as serializable///</summary>///& Lt;param name= "Serializedstr" ></param>///<returns></returns> public static T Deserializesoa
Pformatter<t> (String serializedstr) {SoapFormatter formatter = new SoapFormatter (); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (SERIALIZEDSTR)) {return (T) formatter.
Deserialize (MS);
}} #endregion}}
The specific instance code is as follows:
Download: Demo
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.