Skip to content

Code for Keeps:- Serialization

Another one of my favorites!..Everytime i need to serialize an object i end up surfing the web to get the correct code(who wants to reinvent the wheel!!)

Also most of the time i don’t want to “save” the object on the filesystem but just in memory so my code will focus on saving and reading from memory!

First the simpler one..XMLSerialization

1. XML Serialization

Serialize the object


private void SerializeObject(<ObjectType>obj) { XmlSerializer s = new XmlSerializer(typeof(<ObjectType>)); StringWriter sw = new StringWriter(); s.Serialize(sw, sessionToken); string serializedXml = sw.ToString(); }

Reading from the string


private <ObjectType>ReadFromSerializedString(string s) { XmlSerializer s = new XmlSerializer(typeof( <ObjectType>)); return (<ObjectType>)s.Deserialize(new StringReader(serializedString)); }

However you may not be able to use XMLSerialization on all object types…one irritating requirement is that the object to be serialized should have an parameterless constructor!!. This requirement led me to try Binary serialization….

2. Binary Serialization

Serialize the object


private void SerializeObject(<ObjectType>obj) { var formatter = new BinaryFormatter(); byte[] bytes; using (var stream = new MemoryStream()) { formatter.Serialize(stream, obj ); stream.Seek(0, 0); bytes = stream.ToArray(); } string serializedString = Convert.ToBase64String(bytes); }

Reading from the string


private <ObjectType> ReadSerializedString(string serializedString) { byte[]b =Convert.FromBase64String(serializedString); var formatter = new BinaryFormatter(); <ObjectType> value; using (var stream = new MemoryStream(b, 0, b.Length)) { value = <ObjectType>formatter.Deserialize(stream); } return value; }

Now i won’t have to google my serialization out!..hope this helps you save some time too!

Until Next time!

Cennest!!

Leave a Reply

Your email address will not be published. Required fields are marked *