MVC 4中正确的JSON序列化

Mar*_*rio 43 c# asp.net asp.net-mvc json asp.net-mvc-4

我想让JSON'正确'序列化(camelCase),并且能够在必要时更改日期格式.

对于Web API,它非常简单 - 在Global.asax中,我执行以下代码

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)

这个代码在管道级别按照我喜欢的方式处理序列化.

我想在MVC 4中完成同样的事情 - 从控制器操作方法返回的任何JSON都要正确序列化.通过一点搜索,我发现以下代码将引入Global.asax应用程序启动:

HttpConfiguration config = GlobalConfiguration.Configuration;
Int32 index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonMediaTypeFormatter
{
     SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};
Run Code Online (Sandbox Code Playgroud)

它似乎执行正常,但当我从控制器返回JSON时,它都是PascalCased.我的动作方法的一个简单示例:

private JsonResult GetJsonTest()
{
    var returnData = dataLayer.GetSomeObject();
    return Json(returnData, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

我错了吗?知道如何在管道级别实现这一目标吗?

tec*_*osh 89

我建议使用ServiceStack或Json.NET之类的东西来处理MVC应用程序中的Json输出.但是,您可以轻松编写类并使用基类覆盖Json方法.请参阅下面的示例.

注意:使用此功能,您的Global.ascx.cs文件中不需要任何内容​​.

自定义JsonDotNetResult类:

public class JsonDotNetResult : JsonResult
{
    private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        Converters = new List<JsonConverter> { new StringEnumConverter() }
    };

    public override void ExecuteResult(ControllerContext context)
    {
        if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
            string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("GET request not allowed");
        }

        var response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data == null)
        {
            return;
        }

        response.Write(JsonConvert.SerializeObject(this.Data, Settings));
    }
}
Run Code Online (Sandbox Code Playgroud)

基础控制器类:

public abstract class Controller : System.Web.Mvc.Controller
{
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonDotNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的控制器操作上,您可以简单地返回类似的东西.

return Json(myObject, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)

BAM.你现在有了使用Json返回的camelcase对象:)

注意:有些方法可以使用Json在每个对象上使用Serializer设置来执行此操作.但是每次想要归还Json时谁会想要输入?


fcu*_*sta 6

虽然Web API使用JSON.NET,但MVC4默认使用JavaScriptSerializer,我认为它不支持更改为Camel Case序列化.检查:在ASP.NET MVC中设置默认JSON序列化程序

我的建议是你创建一个自定义的JsonNetResult,如下所述使用JSON.NET作为ASP.NET MVC 3中的默认JSON序列化程序 - 是否可能?并将最后一行更改为:

var serializedObject = JsonConvert.SerializeObject(
      Data,
      Formatting.Indented,
      new JsonSerializerSettings { MappingResolver = new CamelCaseMappingResolver() });
Run Code Online (Sandbox Code Playgroud)


Nee*_*eel 5

Note that below information is for Asp .Net core
Run Code Online (Sandbox Code Playgroud)

.Net团队最近宣布,MVC现在默认情况下使用驼峰式案例名称对JSON进行序列化。

在下面的几行中,您将能够启用此功能:

services
.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.ContractResolver = new DefaultContractResolver());
Run Code Online (Sandbox Code Playgroud)

我在这里写了小博客。

  • 是的,但是它是用于aspnet核心的 (3认同)