Serialization
XML Serialization
Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again.
Some good uses for serialization/deserialization include:
- Storing user preferences in an object.
- Maintaining security information across pages and applications.
- Modification of XML documents without using the DOM.
- Passing an object from on application to another.
- Passing an object from one domain to another.
- Passing an object through a firewall as an XML string.
XML Serialization: It is limited that it can serialize only public members.
Required Namespace :
Imports System.Xml
Imports System.Xml.Serialization
Create XSD file from Class
Object instance into XML file
Create one web project and add Person.vb class file.
Imports System
Imports System.Xml
Imports System.Xml.Serialization
Namespace XMLSerialization
''' <summary>
''' Summary description for Person.
''' </summary>
<XmlRoot("Class_Person")> _
Public Class Person
Private m_sName As String
Private m_iAge As Integer
Public Sub New()
End Sub
<XmlElement("Property_Name")> _
Public Property Name() As String
Get
Return m_sName
End Get
Set(ByVal value As String)
m_sName = value
End Set
End Property
<XmlElement("Property_Age")> _
Public Property Age() As Integer
Get
Return m_iAge
End Get
Set(ByVal value As Integer)
m_iAge = value
End Set
End Property
Public Function Hello() As String
Return "Hi! My name is " + Name + " and I am " + Age.ToString() + " years old"
End Function
Public Function GoodBye() As String
Return "So long"
End Function
End Class
End Namespace
[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place.
Dim objXmlSer As New XmlSerializer(GetType(Person))
Dim objLucky As New Person()
Dim objStrWrt As StreamWriter
objLucky.Name = "Myname"
objLucky.Age = 30
Response.Write(objLucky.Hello())
Response.Write(objLucky.GoodBye())
objStrWrt = New StreamWriter(Server.MapPath("abc.xml"))
objXmlSer.Serialize(objStrWrt, objLucky)
objStrWrt.Close()
First of al, we declare and instantiate an XMLSerializer object. The typeof() function describes what type of object it's going to be serializing. Then we assign Name and Age properties of the Person object. Then we used to see the output of that object by calling Hello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object and send it our person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter.
The Abc.Xml file is look like.
<Xml version="1.0" encoding="utf-8" ?>
<c- <Class_Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Property_Name>TestProperty1 </Property_Name>
<Property_Age>30</Property_Age>
</Class_Person>
Create class object from XML file
XML file into Object instance.
Now, make some changes in your abc.xml file.
<xml version="1.0" encoding="utf-8" ?>
<Class_Person xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance">
<Property_Name>TestProperty2</Property_Name>
<Property_Age>32</Property_Age>
</Class_Person>
First create instance of Person class. Next, we create an instance of StreamReader object and feed it the stored XML file. Then we instantiate the Person object by calling the deserialize() method of the XMLSerializer object. This method use the StreamReader object to read the content of the XML file. You have to explicitly casting the type to Person type.
Dim objDesPerson As New Person()
Dim objStrRdr As StreamReader
objStrRdr = New StreamReader(Server.MapPath("abc.xml"))
Dim objXmlSer As New XmlSerializer(GetType(Person))
objDesPerson = DirectCast(objXmlSer.Deserialize(objStrRdr), Person)
Response.Write(objDesPerson.Name)
Response.Write(objDesPerson.Age.ToString())
objStrRdr.Close()
Binary Serialization
Public Class Article
Public sTitle As String
Public sAuthor As String
Public sText As String
End Class
Not much to this class, just a few string variables. Lets suppose that we need to write an instance of this call tout to disk. To do this, we can use binary serialization. This will create a binary file that can be read back in as an instance of Article. To do this, we will need to implement 2 methods GetObjectData and Overloaded Constructor.
It will requires following namespace:
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
First we will make the class with serializable attribute and implements the ISerializable interface.
[Serializable()]
Public Class Articles
Implements ISerializable
End Class
We have to implements GetObjectData method of ISerializable interface.
Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
info.AddValue("Title", sTitle)
info.AddValue("Author", sAuthor)
info.AddValue("Text", sText)
End Sub
This method will allow you to serialize the objects to disk. We could add any code in here that we wanted to customize the way the data is serialized.
Now we need a method to retrieve the data from a serialized object then we will use a overloaded constructor for this.
Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))
sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))
sText = Convert.ToString(info.GetValue("Text", GetType(String)))
End Sub
The empty constructor is added here so that you can create a new Article object without deserialized one.
Now we have a class that can be serialized and deserialized. For serializing this class we have to create methods like
Serializing the object
Public Sub serialize(ByVal fileName As String)
Dim s As New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)
Dim B As New BinaryFormatter()
B.Serialize(s, Me)
s.Close()
End Sub
Here first we create an instance of FileStream class which, will create file and open it in read and write mode. Next we create an instance of BinaryForamtter class. This class have Seralize method which take parameters FileStream and Instance which you want to serialize.
DeSerializing the object
Public Function deSerialize(ByVal fileName As String) As Articles
Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim F As New BinaryFormatter()
Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)
Fs.Close()
Return s1
End Function
Here again create an instance of BinaryFormatter. The method Deserialize() will take parameter of FileStream object which point to the binary file which you want to deserialize. You have to do explicit casting of Article type during Deserializing.
Create One Project For Serializing
Create one Articles.vb class file
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Namespace BinarySerialization
<Serializable()> _
Public Class Articles
Implements ISerializable
Public sTitle As String
Public sAuthor As String
Public sText As String
Public Sub New()
End Sub
Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))
sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))
sText = Convert.ToString(info.GetValue("Text", GetType(String)))
End Sub
Public Sub serialize(ByVal fileName As String)
Dim s As FileStream
s = New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)
Dim B As New BinaryFormatter()
B.Serialize(s, Me)
s.Close()
End Sub
Public Function deSerialize(ByVal fileName As String) As Articles
Dim Fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim F As New BinaryFormatter()
Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)
Fs.Close()
Return s1
End Function
#Region "ISerializable Members"
Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
info.AddValue("Title", sTitle)
info.AddValue("Author", sAuthor)
info.AddValue("Text", sText)
End Sub
#End Region
End Class
End Namespace
Create one webForm1.aspx page for testing the binary serialization.
'Binary Serialization of the object
Dim c1 As New Articles()
c1.sTitle = "My Title"
c1.sAuthor = "Author Name"
c1.sText = "This is my Text"
c1.serialize("C:\123.txt")
'deserialization of the object
Dim c2 As Articles = c1.deSerialize("C:\123.txt")
Response.Write(c2.sTitle)
Response.Write(c2.sAuthor)
Response.Write(c2.sText)
NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# Corner (http://www.c-sharpcorner.com/).