RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: .NET
Expertise: Intermediate
Nov 24, 2009

Serialize Any .NET Object to a JSON String

The following steps explain how to serialize any .NET object into a JSON string. This tip uses the .NET 3.0 Framework. You'll find this capability particularly helpful in applications that use AJAX to pass objects from the server to the client code.

Assume you have a Person object defined as shown below:

public class Person
  public int ID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

Now assume you need to serialize this object to a JSON string to pass it to a client-side script. It turns out you can easily convert an instance of the Person class (or any .NET object) to a JSON string, by using an "extension method" (a capability released with .NET 3.0). To create a JSON serialization extension method, use the following code:

using System.Web.Script.Serialization;
namespace JSON.Namespace
  public static class JSONHelper
     public static string ToJSON(this object obj)
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);

The JavaScriptSerializer class (in System.Web.Script.Serialization) handles the actual object-to-JSON conversion. Note that the ToJSON() extension method above is defined for type Object, which means you can use it with all .NET objects. This means that in addition to calling ToJSON() on a Person object, you could call it the same way on a collection of Person objects or any other .NET datatype. The following examples show how to use the ToJSON() method:

using JSON.Namespace; //Reference the namespace that contains ToJSON()

Person person = new Person() { 
   ID=1, FirstName="Dev", 
   LastName="Jackson" }; //Create a Person object
   //Convert to a JSON string 
   string JsonString = person.ToJSON();

The output of the preceding code would be:

[{"ID":1, "FirstName":"Dev", "LastName":"Jackson"}]

Conveniently, VS 2008 provides Intellisense and compile-time support for extension methods, just as if they were built-in methods.

Deepak Choudhari
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date