smart developer's blog

This is a C# resource library! Free how to's and best practices…

JSON serialization and deserialization in ASP.net C#

with 3 comments

In ASP.net you can use the JavaScriptSerializer class to serialize and deserialize JSON objects. I am going to demonstrate below how simply it is to do this.
First, save the following code in you application as JSONHelper.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Helpers
{
    /// <summary>
    /// Summary description for JSONHelper
    /// </summary>
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static T FromJSON<T>(string str)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(str);
        }

        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

Now let’s say you have an object called MyObject from a class called MyClass and you want to serialize it. All you have to do is to use:


MyClass MyObject = new MyClass();
string strJson = MyObject.ToJSON();

That’s it! You get a string that you can now store or pass to another resource as you need it.
Now, in order to deserialize a string into an object simply user:


MyClass MyObject = JSONHelper.FromJSON<MyClass>(strJson);

Enjoy!

Written by smartdev

March 29th, 2011 at 2:54 pm

3 Responses to 'JSON serialization and deserialization in ASP.net C#'

Subscribe to comments with RSS or TrackBack to 'JSON serialization and deserialization in ASP.net C#'.

  1. Citeste-l si pe http://www.hanselman.com :)

    GeNe

    12 Apr 11 at 7:55 am

  2. Il am in Google Reader! :)

    smartdev

    12 Apr 11 at 8:00 am

  3. Brilliant post old bean, I really should make time to visit your site more often for some more of these great posts. I really appreciate it.

    kirky

    27 Apr 11 at 2:04 pm

Leave a Reply