Click here to Skip to main content
15,867,938 members
Articles / Web Development / ASP.NET

Switching Seamlessly Between Serialization

Rate me:
Please Sign up or sign in to vote.
4.93/5 (7 votes)
12 Jun 2012CPOL2 min read 25.3K   262   16   2
Swintching between different types of serialization.

Introduction

Serialization is part integral of the big business that this modern, fast pace and connected world has to offer us. Whether you are targeting PC users, or the wireless market, serialization should be part integral of your software strategy. For you to rip the maximum benefits from it, you need to know how to maximize its efficacy. The only way that can happen is to know and have the capabilities to use the type of serialization that's just right for your storage or transfer requirements.

As a general definition, Wikipedia presents serialization as: "In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment".

Background

In this paper we will demonstrate from a .Net environment how you could effectively take advantage of the three main types of serialization that represent the corner stone of data storage and transfer in modern eCommerce affair.

  • JSON: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is based on a subset of the JavaScript Programming Language, which makes it particularly suitable for web programing or anything related to data exchange over the HTTP protocol.
  • Binary serialization: If your serialized object is not going to cross the network but rather saved on disc, this formatter is your choice of excellence to serialize objects specific to the .NET Framework applications.
  • XML serilaization: XML can be used to store any type of data, such pictures, music, binary files, and database information. It is a standardized, text-based document format for storing application-readable information, transmitting objects between computers even if the remote computer is not using the .NET Framework.

Having the ability to switch between these three types of serialization can help you write flexible applications capable to responding to the exigencies of today markets.

Using the code

The main objects of this project are:

  • LibSerialization.cs which has three classes and an interface. You can just drop it into your App_Code folder or compile it into a .dll library.
  • An example of a base ASP.NET page which encapsulates the objects.

The solution includes an ASP.NET example for testing purposes.

The IFomate interface

Which allows us to switch from object to object and expose the contract for different types of serialization formatters.

C#
public interface IFomate
{
    string Seryalize<T>(T obj);
    string Seryalize(object obj);
    byte[] Seryalize(object obj, Type T);
    T Deseryalize<T>(string konteni);
}

The JsonFomate

For this serialization, we use the Newtonsoft library at CodePlex.

C#
public class JsonFomate : IFomate
{
    public JsonFomate(){}

    public string Seryalize<T>(T obj)
    {
        string res = JsonConvert.SerializeObject(obj).FromJsonDateString();
        return Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(res));
    }

    public string Seryalize(object obj)
    {
        string res = JsonConvert.SerializeObject(obj).FromJsonDateString();
        return Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(res));
    }

    public byte[] Seryalize(object obj, Type t)
    {
        string res = JsonConvert.SerializeObject(obj).FromJsonDateString();
        return Encoding.UTF8.GetBytes(res);
    }

    public T Deseryalize<T>(string konteni)
    {
        string res = konteni.ToJsonDateString();
        return JsonConvert.DeserializeObject<T>(res);
    }
}

The XmlFomate class

C#
public sealed class XmlFomate : IFomate
{
    public XmlFomate(){}

    public string Seryalize<T>(T obj)
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xml = new XmlSerializer(typeof(T));
        xml.Serialize(ms, obj);
        return Encoding.UTF8.GetString(ms.GetBuffer());
    }

    public string Seryalize(object obj)
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xml = new XmlSerializer(obj.GetType());
        xml.Serialize(ms, obj);
        return Encoding.UTF8.GetString(ms.GetBuffer());
    }

    public byte[] Seryalize(object obj, Type T)
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xml = new XmlSerializer(T);
        xml.Serialize(ms, obj);
        return Encoding.UTF8.GetBytes(Encoding.Default.GetString(ms.GetBuffer()));
    }

    public T Deseryalize<T>(string konteni)
    {
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(konteni));
        XmlSerializer xml = new XmlSerializer(typeof(T));
        return (T)xml.Deserialize(ms);
    }
}

The BinFomate Class

For binary serialization, we use the BinaryFormatter class which is different from the XmlFomate counterpart which is XmlSerializer.

C#
public sealed class BinFomate : IFomate
{
    public BinFomate(){}

    public string Seryalize<t>(T obj)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bin = new BinaryFormatter();
        bin.Serialize(ms, obj);
        return Encoding.Unicode.GetString(ms.GetBuffer());
    }

    public string Seryalize(object obj)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bin = new BinaryFormatter();
        bin.Serialize(ms, obj);
        return Encoding.Unicode.GetString(ms.GetBuffer());
    }

    public byte[] Seryalize(object obj, Type T)
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bin = new BinaryFormatter();
        bin.Serialize(ms, obj);
        return Encoding.Unicode.GetBytes(Encoding.Unicode.GetString(ms.GetBuffer()));
    }

    public T Deseryalize<t>(string konteni)
    {
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(konteni));
        BinaryFormatter bin = new BinaryFormatter();
        return (T)bin.Deserialize(ms);
    }
}

The DataZouti Class

This is a helper class for date formatting in JSON serialization.

C#
public static class DatZouti
{     
    public static string FromJsonDateString(this string konteni)
    {
        string eksp = @"\\/Date\((\d+)([\+\d]+)?\)\\/";
        Match m = Regex.Match(konteni, eksp);
        if(m.Success)
        {
            string vale = string.Empty;
            string ts = m.Groups[1].Value.ToString();

            DateTime dt = new DateTime(1970,1,1);
            dt = dt.AddMilliseconds(long.Parse(ts)).ToLocalTime();
            vale = Regex.Replace(konteni, eksp, dt.ToString("yyyy-MM-dd HH:mm:ss"));

            if(!string.IsNullOrEmpty(vale)) return vale;
        }
        return konteni;
    }

    public static string ToJsonDateString(this string konteni)
    {
        string eksp = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
        Match m = new Regex(eksp).Match(konteni);
        if(m.Success)
        {
            string vale = string.Empty;
            DateTime dt = DateTime.Parse(m.Value).ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            vale = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            konteni = Regex.Replace(konteni, eksp, vale);
        }
        return konteni;
    }
}

Points of Interest

There are a wealth of scenarios where you can use serialization: such as database back-up, data structure validation, and object encryption to cite just a few.

History

InterSerialization v1.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Mic
Systems Engineer
Haiti Haiti
Studied Computer Engineering System in Mexico, have worked in several companies and also as a freelancer. Now I reside in the U.S. I specialized in Web Application Architecture and Development. My preferred language of programming is C#/Asp.net.

If you see my articles can be of any use to you, encourage by donating:

Donate With Paypal

Other articles of interest:


Switching Seamlessly Between Serialization

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mic17-Nov-12 4:51
Mic17-Nov-12 4:51 
SuggestionInterserialization Pin
Mic1-Nov-12 7:37
Mic1-Nov-12 7:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.