Object Serialization is an interesting subject as so many developers have never had to deal with it. In very basic terms, serialization is simply converting an object to a different format. We know that an object is an instance of a class and nearly always it is stored in memory (invisible to most developers). We get into serialization/deserialization when we need to persist an object to some sort of long-ish term storage (database, file, or ??) or transport it (via HTTP or TCP socket or ??). The most typical (in my experience) forms of serialization are to a binary or an XML representation. Over the past several years, I have written a number of processes that transmit data via TCP sockets (an object “factory/distributor”) with many “clients/subscribers” as well as sending data from a client to a web service (for example). In all but the simplest of implementations, sending a serialized object is the best option.
The .Net Framework provides a great deal of functionality to facilitate object serialization and deserialization. The System.Runtime.Serialization namespace is your friend (and required for the following code samples).
Let’s start with binary serialization:
The easisest example is to serialize (“convert”) an object to a byte array. This can by done as follows:
Dim oByte As Byte()
Dim oMS As New MemoryStream
Dim oBinaryFormatter As New BinaryFormatter
oBinaryFormatter.Serialize(oMS, value)
oByte = oMS.GetBuffer
The question is then, what do I do with a byte array? Well, converting it to a string allows you to persist that string to storage – use System.Object.Convert such as:
Convert.ToBase64String(oByte)
This returns the string that you are looking for and can be persisted.
You now have a binary serialized object that you want to use again. You must deserialize the string into an object (reverse the process). This code performs those steps:
Dim _byteArray As Byte()
Dim _binaryFormatter As New BinaryFormatter
_byteArray = Convert.FromBase64String(_stringValue)
Dim _memorySteam As New MemoryStream(_byteArray)
DeserializeString = oBinaryFormatter.Deserialize(_memorySteam)
Ok, easy. However; when I try this on one of my classes, it fails with something like: “Type ‘WindowsApplication1.Form1’ in Assembly ‘WindowsApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ is not marked as serializable.”
This is easily solved. All classes that are to be serialized must be marked with the serializeable attribute like so:
<Serializable()> Public Class MyClass
That is the basics of binary object serialization and deserialization. The terms sounds very “fancy” but in reality, it is just a conversion to a form that can be saved or transported – Easy!
Leave a Reply