Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON using C# like PHP json_encode

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?

like image 252
Cameron Avatar asked Jan 26 '12 10:01

Cameron


2 Answers

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.

like image 95
Darin Dimitrov Avatar answered Sep 28 '22 17:09

Darin Dimitrov


I always use JSON .Net: http://json.codeplex.com/ and the documentation: http://james.newtonking.com/projects/json/help/

like image 31
hyp Avatar answered Sep 28 '22 19:09

hyp