在设置ASP.NET MVC默认JSON序列 [英] Setting the Default JSON Serializer in ASP.NET MVC
问题描述
我有一个很难找到这个问题的答案:
I'm having a hard time finding the answer to this:
我的工作已部分转化到MVC现有的应用程序。每当控制器一个JSON的ActionResult响应时,Enum也相对于字符串名称号码发送。这听起来像默认的序列化应该是JSON.Net,应在发送枚举,而不是重新presentation整数自己的名字,但这里并非如此。
I'm working on an existing application that has been partially converted over to MVC. Whenever a controller responds with a JSON ActionResult, the enums are sent as numbers opposed to the string name. It sounds like the default serializer should be JSON.Net, which should be sending the enums over as their names opposed to the integer representation, but that's not the case here.
我缺少一个web.config设置,该设置为默认的序列化?或者是有需要改变另一个设置?
Am I missing a web.config setting that sets this as the default serializer? Or is there another setting that needs to be changed?
推荐答案
在ASP.Net MVC4默认的JavaScript串行这是在 JsonResult
类使用仍然是<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSerializer (你可以检查它的<一个href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/JsonResult.cs\">$c$c)
In ASP.Net MVC4 the default JavaScript serializer which is used in the JsonResult
class is still the JavaScriptSerializer (you can check it in the code)
我想你已经与ASP.Net Web.API混淆它放在JSON.Net是默认的JS串行但MVC4不使用它。
I think you have confused it with the ASP.Net Web.API where JSON.Net is the default JS serializer but MVC4 doesn't use it.
所以,你需要配置JSON.Net与MVC4(基本上你需要创建自己的 JsonNetResult
),有很多关于它的文章的工作:
So you need to configure JSON.Net to work with MVC4 (basically you need to create your own JsonNetResult
), there are plenty of articles about it:
- ASP.NET MVC and Json.NET
- Using JSON.net as default JSON serializer in ASP.NET MVC 3 - Is it possible?
如果你也想用JSON.Net的控制器操作参数,以便在模型绑定,那么你需要编写自己的 ValueProviderFactory
的实施。
If you also want to use JSON.Net for controller action parameters so during the model binding then you need write your own ValueProviderFactory
implementation.
而你需要注册与您的实现:
And you need to register your implementation with:
ValueProviderFactories.Factories
.Remove(ValueProviderFactories.Factories
.OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
您可以使用内置的 JsonValueProviderFactory
作为一个例子或文章:<一href=\"http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/\">ASP.NET MVC 3 - 改进JsonValueProviderFactory使用Json.Net
You can use the built in JsonValueProviderFactory
as an example or this article: ASP.NET MVC 3 – Improved JsonValueProviderFactory using Json.Net
这篇关于在设置ASP.NET MVC默认JSON序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!