Serialize and Deserialize objects as Xml using generic types in VB.Net
Posted by anoriginalidea on August 10, 2009
In his blog post Serialize and deserialize objects as xml using generic types in C# 2.0 , Paul Whitaker creates some ubiquitous functions for doing Xml Serialization with generics.
To serialize:
Dim lsXml As String = GenericXmlSerializer.SerializeObject(of MyObjectType)(myObject)
To deserialize:
Dim myObject As MyObjectType = GenericXmlSerializer.DeserializeObject(of MyObjectType)(lsXml)
Here’s the code
Imports System.Collections.Generic Class GenericXmlSerializer Dim encoding As New UTF8Encoding End Function ''' <summary> Dim encoding As New UTF8Encoding() ''' <summary> Try Dim memoryStream As New MemoryStream() Return xmlString Return String.Empty ''' <summary> Dim xs As New XmlSerializer(GetType(T)) Dim theObject As T = CType(xs.Deserialize(memoryStream), T) End Function End Class
Imports System.Text
Imports System.Xml
Imports System.IO
Imports System.Xml.Serialization
''' <summary>
''' To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
''' </summary>
''' <param name="characters">Unicode Byte Array to be converted to String</param>
''' <returns>String converted from Unicode Byte Array</returns>
Public Shared Function UTF8ByteArrayToString(ByVal characters As Byte()) As String
Dim constructedString As String = encoding.GetString(characters)
Return constructedString
''' Converts the String to UTF8 Byte array and is used in De serialization
''' </summary>
''' <param name="pXmlString"></param>
''' <returns></returns>
Public Shared Function StringToUTF8ByteArray(ByVal pXmlString As String) As Byte()
Dim byteArray As Byte() = encoding.GetBytes(pXmlString)
Return byteArray
End Function
''' Serialize an object into an XML string
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="obj"></param>
''' <returns></returns>
Public Shared Function SerializeObject(Of T)(ByVal obj As T) As String
Dim xmlString As String = Nothing
Dim xs As New XmlSerializer(GetType(T))
Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
xs.Serialize(xmlTextWriter, obj)
memoryStream = CType(xmlTextWriter.BaseStream, MemoryStream)
xmlString = UTF8ByteArrayToString(memoryStream.ToArray())
memoryStream.Dispose()
Catch
End Try
End Function
''' Reconstruct an object from an XML string
''' </summary>
''' <param name="xml"></param>
''' <returns></returns>
Public Shared Function DeserializeObject(Of T)(ByVal xml As String) As T
Dim memoryStream As New MemoryStream(StringToUTF8ByteArray(xml))
Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
memoryStream.Dispose()
Return theObject
Rather than be original, I converted most of his code verbatim and have found the functions useful.
I offer them to you warranty free, unadorned and hopefully useful.

