在 MVC 4 中将对象转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12821078/
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
Convert Object to JSON in MVC 4
提问by user1735105
I am converting an object to JSON using JavaScriptSerializerand I can see this JSON output in server code:
我正在使用将一个对象转换为 JSON JavaScriptSerializer,我可以在服务器代码中看到这个 JSON 输出:
[{"UserId":1,"UserName":"Admin"}]
But in the UI it's getting converted to something like below
但是在 UI 中,它被转换为如下所示的内容
[{"UserId":1,"UserName":"Admin"}].
How to escape those "?
怎么躲开那些"?
回答by Darin Dimitrov
If you are using the Razor view engine you need to use the Html.Rawmethod:
如果您使用 Razor 视图引擎,则需要使用以下Html.Raw方法:
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
</script>
Notice the usage of the Json.Encodemethod which is shorter and equivalent to new JavaScriptSerializer().Serialize().
请注意Json.Encode更短且等效于的方法的用法new JavaScriptSerializer().Serialize()。
回答by Erik Funkenbusch
Why are you doing that? Why not just return a JsonResult?
你为什么这样做?为什么不只返回一个JsonResult?
public ActionResult MyMethod()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { UserId = "1", UserName = "Admin" },
new ListItem() { UserId = "2", UserName = "JohnDoe" },
new ListItem() { UserId = "3", UserName = "JaneDoe" }};
return this.Json(list);
}
回答by Fenwick
Just one more thing on Darin Dimitrov's answer. In my VS2012 there is a compilation error with the semicolon, cuz the statement from JS side is actually "var model = ;". A way around using a pair of quotation to wrap the Razor part like this:
关于 Darin Dimitrov 的回答还有一件事。在我的 VS2012 中,分号存在编译错误,因为 JS 端的语句实际上是“var model = ;”。一种使用一对引号来包装 Razor 部分的方法,如下所示:
var model = "@Html.Raw(Json.Encode(Model))";
This will not cause any error.
这不会导致任何错误。
Json.Encode() seems to be a wrapper function of JavaScriptSerializer. I'm not sure if the latter is more time efficient.
Json.Encode() 似乎是 JavaScriptSerializer 的包装函数。我不确定后者是否更省时。

