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: This is a compact and efficient format for .NET-to-.NET communication. It's generally faster than XML serialization but is not human-readable and is version-sensitive.
- XML Serialization: This serializes objects into an XML format. It's human-readable, widely interoperable, and suitable for transferring data between different applications and platforms.
- JSON Serialization: While not built into the core .NET Framework in the same way as Binary and XML, JSON serialization is extremely popular for web APIs and modern applications. You'll typically use libraries like
System.Text.Json
(in .NET Core/.NET 5+) or Newtonsoft.Json.
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
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 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
Considerations for Serialization
[Serializable]
Attribute: Required forBinaryFormatter
. Not strictly necessary forXmlSerializer
but can be used for control.- Data Contracts: For WCF services, use Data Contracts (
[DataContract]
and[DataMember]
attributes) which are more robust and flexible. - Performance: Binary serialization is generally fastest. JSON can be very fast with optimized libraries. XML can be slower due to its verbose nature.
- Interoperability: XML and JSON are excellent for interoperability between different systems and languages. Binary is primarily for .NET-to-.NET.
- Security: Be cautious with deserializing data from untrusted sources, especially with
BinaryFormatter
.