JSON Serialization and Deserialization in C# with Extension Method

Starting its 3.5 framework, .Net has already support JSON object serialization from System.Web.Script.Serialization.JavaScriptSerializer namespace.

Please note that the code below is an extension method to add ToJson() method to my object.

public static class JsonExtensionMethod
{
    public static string ToJson(this object o)
    {
        System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        return jsonSerializer.Serialize(o);
    }

    public static T FromJson<T>(this string s)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        return serializer.Deserialize<T>(s);
    }
}

The usage is pretty simple and straight-forward. All we need to do is create JavaScriptSerializer instance and call its Serialize method. The method takes object type as its parameter which mean, you can pass all types that derive from System.Object.

To deserialize it, we use Deserialize method of JavaScriptSerializer class.

According to Scott Gu’s post, System.Web.Script.Serialization.JavaScriptSerializer is obsoleting, but will still be available in few versions to come.

Beside System.Web.Script.Serialization.JavaScriptSerializer, you also can use new System.Runtime.Serialization.DataContractJsonSerializer class

Advertisements

3 thoughts on “JSON Serialization and Deserialization in C# with Extension Method”

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s