我正在开发一个已部分转换为 MVC 的现有应用程序.每当控制器以 JSON ActionResult 响应时,枚举都会作为数字而不是字符串名称发送.听起来默认的序列化程序应该是 JSON.Net,它应该将枚举作为它们的名称发送过来,而不是整数表示,但这里不是这种情况.
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 中,JsonResult
类中使用的默认 JavaScript 序列化器仍然是 JavaScriptSerializer (你可以在 代码)
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:
如果您还想将 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.
你需要注册你的实现:
ValueProviderFactories.Factories
.Remove(ValueProviderFactories.Factories
.OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
您可以使用内置的 JsonValueProviderFactory
作为示例或这篇文章:ASP.NET MVC 3 – 使用 Json.Net 改进的 JsonValueProviderFactory
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 序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!