Object Serialization, which is also called deflating or marshaling, is a progression through which an object’s state is converted into some serial data format, such as XML or binary format, in order to be stowed for some advanced use whereas Deserialization is the opposite process of Serialization which is also called inflating or unmarshalling. The code showing the very simple way for serializing and deserializing from XML to any Object and vice versa as well,
Use this method for serialization,
public static string Serialize<T>(T value)
{
if (value == null)
{
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false);
settings.Indent = false;
settings.OmitXmlDeclaration = false;
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
Use this method for Deserialization:
public static T Deserialize<T>(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml))
{
using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
{
return (T)serializer.Deserialize(xmlReader);
}
}
}