Return JSON using C# like PHP json_encode

2019-01-25 14:40发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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



回答4:

The simplest way it may be like this:

public JsonResult GetData()
{      
    var myList = new List<MyType>();

    //populate the list

    return Json(myList);
}