advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 2.4/5 | Rate this item | 25 users have rated this item.
Expertise: Intermediate
Language: .NET
November 23, 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
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement