Serialization and Deserialization in VB.NET

Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format.

The reverse process of Serialization is De Serialization.

For the process of serialization we need two things. One is a Formatter and another is a Stream Object.
The class written below is the class whose object is going to be serialized. For that purpose, the attribute are added.

Public Class DataDescription

Public Data As Integer
Public Description As String

Public Sub New(ByVal NewData As Integer, ByVal NewDescription As String)
Data = NewData
Description = NewDescription
End Sub

Public Overrides Function ToString() As String

Return Description

End Function

End Class

Serialization function is…

Public Function SerializeData(ByVal oDataToBeSerialized As Object) As System.IO.MemoryStream

Dim oFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()

Dim oStream As New System.IO.MemoryStream()
oFormatter.Serialize(oStream, oDataToBeSerialized)
Return oStream

End Function


Deserialization is the process of using the serialized state information to regain the object from the serialized shape to its original shape.

So, it is basically the reverse process of the Serialization. (The name also suggests De-Serialization)

Public Function DeSerializeData(ByVal oStream As System.IO.MemoryStream) As Object
Dim oFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim oReturnObject As Object
oStream.Position = 0
oReturnObject = oFormatter.Deserialize(oStream)
Return oReturnObject
End Function



No comments: