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 to make equivalent in C # ASP.NET MVC3 in the simplest way?

+6
source share
4 answers

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() { // it 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 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 .

+8
source
+4
source

What about http://www.json.org/ (see C # list)?

+3
source

The easiest way could be this:

 public JsonResult GetData() { var myList = new List<MyType>(); //populate the list return Json(myList); } 
+2
source

Source: https://habr.com/ru/post/906921/


All Articles