Have you looked at the JavaScriptSerializer class? It will create a JSON version of a .NET type, including any public properties and a __type property so that the object can be reconstructed/deserialized when necessary.
Also not that WebMethods return JSON, which makes it incredibly convenient to send objects back and forth from AJAX to the server.
EDIT: added some example code in response to OP's comments.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
The method GetDate() above is a webmethod. Note that it has the [WebMethod] attribute applied, and that it is static. Note that the page in which a webMethod resides will call it's page_load() method each time you call one of its webMethods. Code your pages accordingly.
To call a webMethod from JavaScript, you can use jQuery:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Replace the div's content with the page method's return.
alert('Received from webmethod: '+result.d);
}
});
The example webMethod here returns a string, but just about any object type can be returned instead. There are many good references in SO, as well as around the .NET, on using webMethods.
If you don't need the power of a webMethod and, instead, wish only to serialize an object into JSON, just use the JSON serializer:
public string MyClassToJson(MyClass mc)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serializedObject = serializer.Serialize(mc);
return serializedObject;
}