Generic Method for Deserilization and Serialization in C#

The below code will serialize an object into JSON and deserialize that JSON back into the object using Generic Method.

Adding the Namespace

using
System.Runtime.Serialization.Json;

Generic Json Serialization

public static string JsonSerializer<T>(T t)
{
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
}  

Generic Json Deserialization

public static T JsonDeserialize<T>(string jsonString)
{
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
}

Calling the Methods.

protected void Page_Load(object sender, EventArgs e)
{  
        Person p = new Person();
        p.Name = "Tony";
        p.Age = 23;
        string jsonString = JsonSerializer<Person>(p);
        Response.Write(jsonString);       
        Person pp = JsonDeserialize<Person>(jsonString );
 }

public class
Person
{
        public string Name { get; set; }
        public int Age { get; set; }
}

Ebook Download
View all
Learn
View all