You can use the JavaScriptSerializer class, which is built into the framework. For instance:
var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(new { param1 = "data1", param2 = "data2" });
gives:
{"param1":"data1","param2":"data2"}
But since you talked about returning JSON to ASP.NET MVC 3, there are already built-in methods that allow you to directly return objects and have a basic infrastructure, taking care of serializing this object in JSON, to avoid plumbing your code.
For example, in ASP.NET MVC 3, you simply write a controller action that returns JsonResult :
public ActionResult Foo() {
You no longer need to worry about plumbing. In ASP.NET MVC, you have controller actions that return action results, and you pass view models to these results. In the case of JsonResult, this is the basic infrastructure that takes care of serializing the view model that you passed in the JSON string, and in addition to that, correctly set the Content-Type response header to application/json .
source share