Categories
.NET C# Utility

Serialize and Deserialize POCO classes in XML

Serialize and Deserialize the Plain Old CLR Object (POCO) class is the theme of this post and I will be discussing regarding XML-based Serialization and Deserialization.

Note: This post is purely about Serialization and not regarding how to write Serializable POCO classes.

Image Illustration

Serialization Mechanism
Shows overall process of Serialization

POST Index

  1. Serialization
  2. Deserialization
  3. Uses
  4. Download Source code

 

For Serialization

DEFINITION

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment. Also known as deflating or marshalling.

Source: Wikipedia

Conversion

POCO class to String

Steps

  1. Input POCO class instance
  2. Declare Encoding such as ASCII, UTF-8, and BigEndianUnicode, or else
  3. Declare Stream for In-Memory Serialization
  4. Declare Serializer
  5. Execute Serialization method
  6. Fetch the serialized XML
  7. Output is String value ( XML value )

Source Code

public static string XmlSerialize(T sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (sourceValue == null)
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	string targetValue;

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream())
	{
		// Declare Stream with required Encoding
		using (var streamWriter = new StreamWriter(memoryStream, encoding))
		{
			// Declare Xml Serializer with source value Type (serializing type)
			var xmlSerializer = new XmlSerializer(sourceValue.GetType());

			// Perform Serialization of the source value and write to Stream
			xmlSerializer.Serialize(streamWriter, sourceValue);

			// Grab the serialized string
			targetValue = encoding.GetString(memoryStream.ToArray());
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

FOR DESERIALIZATION

DEFINITION

The opposite operation of Serialization, i.e. extracting a data structure from a series of bytes, is deserialization. Also known as inflating or unmarshalling.

Source: Wikipedia

CONVERSION

String to POCO Class

STEPS

  1. Input String value ( XML value )
  2. Declare Encoding
  3. Declare Serializer
    • Same Serializer class is used for Serializing and Deserializing
  4. Declare Stream for In-Memory Deserialization
  5. Execute Deserialization method
  6. Type cast the return Object to POCO type
  7. Output is POCO class instance

Source CODE

public static T XmlDeserialize(string sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (string.IsNullOrWhiteSpace(sourceValue))
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	T targetValue;

	// Declare Xml Serializer with target value Type (serialized type)
	var xmlSerializer = new XmlSerializer(typeof(T));

	// Get the source value to bytes with required Encoding
	byte[] sourceBytes = encoding.GetBytes(sourceValue);

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream(sourceBytes))
	{
		// Read stream into XML-based reader
		using (var xmlTextReader = new XmlTextReader(memoryStream))
		{
			// Perform Deserialization from the stream and Convert to target type
			targetValue = xmlSerializer.Deserialize(xmlTextReader) as T;
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

Uses

  1. For Deep Cloning the objects
  2. For integrating with RESTful API and Remoting Services
  3. For persisting the User Data for Offline apps which later uses various Synchronization methods
  4. In .NET apps, Serialization is used for saving and accessing settings from web.config or app.config
  5. Remote procedure calls ( RPC )
  6. In Distributed Memory Applications, such AppFabric for Windows Server which is used for Middle tier caching in Load balancing situation
  7. For Data Exchange in cross-platform applications such as .NET apps integration with Android apps or Windows Phone apps.

 

Download Source Code