In PHP to return some JSON I would do:
return json_encode(array('param1'=>'data1','param2'=>'data2'));
how do I do the equivalent in C# ASP.NET MVC3 in the simplest way?
You could use the JavaScriptSerializer class which is built-in the framework. For example:
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new { param1 = "data1", param2 = "data2" });
yields:
{"param1":"data1","param2":"data2"}
But since you talked about returning JSON in ASP.NET MVC 3 there are already built-in techniques that allow you to directly return objects and have the underlying infrastructure take care of serializing this object into JSON to avoid polluting your code with such plumbing.
For example in ASP.NET MVC 3 you simply write a controller action returning a JsonResult
:
public ActionResult Foo()
{
// it's an anonymous object but you could have used just any
// view model as you like
var model = new { param1 = "data1", param2 = "data2" };
return Json(model, JsonRequestBehavior.AllowGet);
}
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 those action results. In the case of JsonResult it's the underlying infrastructure that will take care of serializing the view model you passed to a JSON string and in addition to that properly set the Content-Type
response header to application/json
.
I always use JSON .Net: http://json.codeplex.com/ and the documentation: http://james.newtonking.com/projects/json/help/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With