JSON serialization and deserialization

JSON stands for Javascript Object Notation and this is the new lightweight (then XML) standart for transferring data from one point to another over the network.  Here you can find a sample web page codebehind to see usage in C#.

namespace Prototype
{
    public partial class Json : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //create instance of the object
            SampleObject sampleObject = new SampleObject();

            //Json Serialize
            string json = Functions.ToJson<SampleObject>(sampleObject);

            Response.Write(string.Format("Json result: {0}<br/>",Server.HtmlEncode(json)));

            SampleObject deserializedSampleObject = Functions.FromJson<SampleObject>(json);//Json Deserialize
            Response.Write(string.Format("Object Result: {0}<br/>", deserializedSampleObject.ToString()));

        }
    }

    [Serializable]
    public class SampleObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string EMail { get; set; }

        public SampleObject()
        {
            this.Id = 2345;
            this.Name = "Ozan K.";
            this.Surname = "BAYRAM";
            this.EMail = "xyz@abc.com";
        }

        public override string ToString()
        {
            return string.Format("{0} {1}", Name, Surname);
        }
    }
}

Static methods in ‘Functions‘ class

/// <summary>
/// Serializes to Json string
/// Class must be serializable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ObjectToSerialize"></param>
/// <returns>json string</returns>
public static string ToJson<T>(object ObjectToSerialize)
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream();
    ser.WriteObject(ms, ObjectToSerialize);

    string json = Encoding.Default.GetString(ms.ToArray());
    ms.Close();

    return json;

}

/// <summary>
/// Deserializes json string to object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="JsonString"></param>
/// <returns></returns>
public static T FromJson<T>(string JsonString)
{
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonString));

    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    T returnObject = (T)ser.ReadObject(ms);
    ms.Close();

    return returnObject;
}

Happy codings…

Posts created 141

Leave a Reply

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top