In PHP to return some JSON I would do:
return json_encode(array(\'param1\'=>\'data1\',\'param2\'=>\'data2\'));
how do I do the equivalent
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
.
The simplest way it may be like this:
public JsonResult GetData()
{
var myList = new List<MyType>();
//populate the list
return Json(myList);
}
I always use JSON .Net: http://json.codeplex.com/ and the documentation: http://james.newtonking.com/projects/json/help/
What about http://www.json.org/ (see C# list) ?