VB.NET Serialization

Serialization is the process of converting an object into a stream of bytes that can be stored in a file or memory, or transmitted across a network connection. The process of recreating the original object from the stream is called deserialization.

VB.NET provides several mechanisms for serialization, each with its own advantages and use cases. The most common are:

Binary Serialization

Binary serialization uses the BinaryFormatter class from the System.Runtime.Serialization.Formatters.Binary namespace. To be serialized, a class must be marked with the [Serializable] attribute.

Example: Binary Serialization


Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

<Serializable()>
Public Class Person
    Public Property Name As String
    Public Property Age As Integer
End Class

Public Module SerializationDemo
    Sub Main()
        Dim person As New Person() With {
            .Name = "Alice",
            .Age = 30
        }

        Dim formatter As New BinaryFormatter()
        Dim stream As FileStream = Nothing

        Try
            ' Serialize the object to a file
            stream = New FileStream("person.bin", FileMode.Create)
            formatter.Serialize(stream, person)
            Console.WriteLine("Object serialized successfully to person.bin")

            ' Deserialize the object from the file
            stream = New FileStream("person.bin", FileMode.Open)
            Dim deserializedPerson As Person = CType(formatter.Deserialize(stream), Person)
            Console.WriteLine($"Deserialized: Name={deserializedPerson.Name}, Age={deserializedPerson.Age}")

        Catch ex As Exception
            Console.WriteLine("An error occurred: " & ex.Message)
        Finally
            stream?.Close() ' Ensure the stream is closed
        End Try
    End Sub
End Module
        
Note: Binary serialization is not recommended for untrusted data, as it can be vulnerable to security attacks if malicious code is embedded in the serialized stream.

XML Serialization

XML serialization is performed using the XmlSerializer class from the System.Xml.Serialization namespace. Classes do not require a special attribute, but you can use attributes like [XmlRoot] and [XmlElement] to control the XML output.

Example: XML Serialization


Imports System.IO
Imports System.Xml.Serialization

Public Class Product
    Public Property Id As Integer
    Public Property Name As String
    Public Property Price As Decimal
End Class

Public Module XmlSerializationDemo
    Sub Main()
        Dim product As New Product() With {
            .Id = 101,
            .Name = "Laptop",
            .Price = 1200.50D
        }

        Dim serializer As New XmlSerializer(GetType(Product))
        Dim writer As TextWriter = Nothing

        Try
            ' Serialize the object to an XML file
            writer = New StreamWriter("product.xml")
            serializer.Serialize(writer, product)
            Console.WriteLine("Object serialized successfully to product.xml")

            ' Deserialize the object from the XML file
            Dim reader As TextReader = New StreamReader("product.xml")
            Dim deserializedProduct As Product = CType(serializer.Deserialize(reader), Product)
            Console.WriteLine($"Deserialized: ID={deserializedProduct.Id}, Name={deserializedProduct.Name}, Price={deserializedProduct.Price}")

        Catch ex As Exception
            Console.WriteLine("An error occurred: " & ex.Message)
        Finally
            writer?.Close()
        End Try
    End Sub
End Module
        
XML Output (product.xml):

<?xml version="1.0" encoding="utf-8"?>
<Product>
  <Id>101</Id>
  <Name>Laptop</Name>
  <Price>1200.50</Price>
</Product>
            

JSON Serialization

For JSON serialization, you'll typically use the System.Text.Json namespace in modern .NET versions or the popular Newtonsoft.Json (Json.NET) library. These libraries offer flexible options for customizing JSON output.

Example: JSON Serialization (using System.Text.Json)


Imports System.Text.Json

Public Class Customer
    Public Property CustomerId As Integer
    Public Property FirstName As String
    Public Property LastName As String
    Public Property Email As String
End Class

Public Module JsonSerializationDemo
    Sub Main()
        Dim customer As New Customer() With {
            .CustomerId = 5001,
            .FirstName = "John",
            .LastName = "Doe",
            .Email = "john.doe@example.com"
        }

        ' Serialize to JSON string
        Dim jsonString As String = JsonSerializer.Serialize(customer, New JsonSerializerOptions With {.WriteIndented = True})
        Console.WriteLine("Serialized JSON:")
        Console.WriteLine(jsonString)

        ' Deserialize from JSON string
        Dim deserializedCustomer As Customer = JsonSerializer.Deserialize(Of Customer)(jsonString)
        Console.WriteLine($"Deserialized: ID={deserializedCustomer.CustomerId}, Name={deserializedCustomer.FirstName} {deserializedCustomer.LastName}")
    End Sub
End Module
        
Tip: For cross-platform compatibility and web services, JSON serialization is often the preferred choice.

Considerations for Serialization