Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5
page 3 of 5
by Scott Guthrie
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22618/ 65

Implementing the ToJSON Extension Method

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.

View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2023 ASPAlliance.com  |  Page Processed at 2023-09-24 12:42:38 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search