Monday, June 11, 2012

How to serialize and deserialize any object to a compressed string

How to : Serialize and Deserialize a object into a compressed string

If you have ever needed to serialize some sort of object to a string for whatever reason we always trying to google some example of how to do it correctly. In the example below, I am going to serialize and compress a generic list to a string.

Serialization and Compression

        private static string CompressValue(object serializedValue)
        {
            try
            {
                BinaryFormatter bf = new BinaryFormatter();

                using (MemoryStream ms = new MemoryStream())
                {
                    bf.Serialize(ms, serializedValue);

                    byte[] inbyt = ms.ToArray();

                    using (MemoryStream objStream = new MemoryStream())
                    {
                        using (DeflateStream objZS = new DeflateStream(objStream, CompressionMode.Compress))
                        {
                            objZS.Write(inbyt, 0, inbyt.Length);
                            objZS.Flush();
                            objZS.Close();

                            byte[] b = objStream.ToArray();

                            return Convert.ToBase64String(b);
                        }
                    }
                }
            }
            catch { return string.Empty; }
        }

Deserialize object

        private List DeSerializeStringToObject(string serializedContent)
        {
            List retval = new List();

            byte[] bytCook = Convert.FromBase64String(serializedContent);

            using (MemoryStream inMs = new MemoryStream(bytCook))
            {
                inMs.Seek(0, 0);

                using (DeflateStream zipStream = new DeflateStream(inMs, CompressionMode.Decompress, true))
                {
                    byte[] outByt = ReadFullStream(zipStream);

                    zipStream.Flush();
                    zipStream.Close();

                    using (MemoryStream outMs = new MemoryStream(outByt))
                    {
                        outMs.Seek(0, 0);

                        BinaryFormatter bf = new BinaryFormatter();

                        retval = (List)bf.Deserialize(outMs, null);
                    }
                }
            }

            return retval;
        }

        private static byte[] ReadFullStream(Stream stream)
        {
            byte[] buffer = new byte[32768];

            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
And that is it, you can now serialized any object into a string and deserialize into your object again.

Happy coding guys...