Implementing a basic ToJSON() extension method is pretty
simple. All I needed to-do was use the JavaScriptSerializer class in the
System.Web.Script.Serialization namespace, and define two extension methods
like below. One of the methods serializes an object graph any levels deep, the
other is an overloaded version that allows you to optionally constrain how deep
it recurses (for example: ToJSON(2) would serialize only 2 levels deep in the
object graph).
Figure 5
Note that the ToJSON() extension methods
above are defined for type "Object" - which means they can be
used with all objects in .NET (not just collections). This means that in
addition to calling .ToJSON() on collections like I did above, I could also
have called ToJSON() on individual Person objects, as well as any other .NET
datatype.
To use the extension method, all I need to-do
is add a using statement at the top of my program that references the
namespace it was defined within:
Figure 6
VS 2008 then takes care of providing
intellisense and compile time support for it to all objects:
Figure 7
Note: In addition to the JavaScriptSerializer class, .NET
3.5 also now includes a new
System.Runtime.Serialization.DataContractJsonSerializer class that
you can use for JSON serialization/deserialization.