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!!

Advertisements

About Cennest
Cennest is the brainchild of a group of IT Professionals keen to try their hand in the world of IT Freelancing. After working in the corpora

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: