像 PHP json_encode 一样使用 C# 返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9016595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:36:07  来源:igfitidea点击:

Return JSON using C# like PHP json_encode

c#phpjsonasp.net-mvc-3

提问by Cameron

In PHP to return some JSON I would do:

在 PHP 中返回一些 JSON 我会这样做:

return json_encode(array('param1'=>'data1','param2'=>'data2'));

return json_encode(array('param1'=>'data1','param2'=>'data2'));

how do I do the equivalent in C# ASP.NET MVC3 in the simplest way?

如何以最简单的方式在 C# ASP.NET MVC3 中执行等效操作?

回答by Darin Dimitrov

You could use the JavaScriptSerializerclass which is built-in the framework. For example:

您可以使用框架内置的JavaScriptSerializer类。例如:

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.

但是由于您谈到在 ASP.NET MVC 3 中返回 JSON,已经有内置技术允许您直接返回对象并让底层基础设施负责将此对象序列化为 JSON 以避免此类管道污染您的代码。

For example in ASP.NET MVC 3 you simply write a controller action returning a JsonResult:

例如,在 ASP.NET MVC 3 中,您只需编写一个控制器操作,返回一个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-Typeresponse header to application/json.

您不再需要担心管道问题。在 ASP.NET MVC 中,您具有返回操作结果的控制器操作,并将视图模型传递给这些操作结果。在 JsonResult 的情况下,底层基础设施将负责序列化您传递给 JSON 字符串的视图模型,此外还将Content-Type响应标头正确设置为application/json.

回答by coffee_machine

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

什么http://www.json.org/(见C#列表)?

回答by hyp

回答by dexter

The simplest way it may be like this:

最简单的方法可能是这样的:

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

    //populate the list

    return Json(myList);
}