How to DeSerialize an Object

To DeSerialize an object you need an instance of StringReader, XmlReader and XmlSerializer class in order to read the xml data (Serialized data), read it into XmlReader and DeSerialize it respectively. So in brief my function to DeSerialize the object looks like following.

private object DeSerializeAnObject(string xmlOfAnObject) {
	MyClass myObject = new MyClass();
	System.IO.StringReader read = new StringReader(xmlOfAnObject);
	System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType());
	System.Xml.XmlReader reader = new XmlTextReader(read);
	try {
		myObject = (MyClass) serializer.Deserialize(reader);
		return myObject;
	} catch {
		throw;
	} finally {
		reader.Close();
		read.Close();
		read.Dispose();
	}
}

This function  return an object so to covert that object into my class I will have to unbox it. In order to avoid boxing and unboxing, you can simply specify your class name as a parameter to these functions. To get my class from serialized xml I will call above function like following and extract its properties or use in the way i want.

MyClass deSerializedClass = (MyClass) DeSerializeAnObject(xmlObject);
string name = deSerializedClass.name;
string address = deSerializedClass.address;

 

Tagged . Bookmark the permalink.

Leave a Reply