在 ASP.NET MVC 中设置默认的 JSON 序列化程序 [英] Setting the default JSON serializer in ASP.NET MVC

查看:36
本文介绍了在 ASP.NET MVC 中设置默认的 JSON 序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理已部分转换为 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 序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆