問題描述
我正在開發一個已部分轉換為 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:
- ASP.NET MVC和 Json.NET
- 使用 JSON.NET 作為 ASP.NET MVC 3 中的默認 JSON 序列化程序 - 可能嗎?
如果您還想將 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 序列化程序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!