MVC 4 中正确的 JSON 序列化 [英] Proper JSON serialization in MVC 4

查看:21
本文介绍了MVC 4 中正确的 JSON 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对 JSON 进行正确"序列化(camelCase),并在必要时能够更改日期格式.

I'd like to have JSON 'properly' serialized (camelCase), and the ability to change date formats if necessary.

对于 Web API,这很容易 - 在 Global.asax 中我执行以下代码

For Web API it is very easy - in the Global.asax I execute the following code

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

This code, at the pipeline level, handles serialization the way I'd like.

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

I would like to accomplish the same thing in MVC 4 - have any JSON returned from controller action methods to be serialized properly. With a little searching I found the following code to throw in the Global.asax application startup:

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

它似乎执行得很好,但是当我从控制器返回 JSON 时,它全部是 PascalCased.我的操作方法的一个简单示例:

It seems to execute fine but when I return JSON from a controller it is all PascalCased. A simple example of my action method:

private JsonResult GetJsonTest()
{
    var returnData = dataLayer.GetSomeObject();
    return Json(returnData, JsonRequestBehavior.AllowGet);
}

我这样做错了吗?知道如何在管道级别完成此任务吗?

Am I going about this wrong? Any idea how to accomplish this at the pipeline level?

推荐答案

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

I would recommend using something like ServiceStack or Json.NET for handling Json output in your MVC application. However, you can easily write a class and override the Json method using a base class. See my example below.

注意:有了这个,您的 Global.ascx.cs 文件中不需要任何内容​​.

NOTE: With this, you do not need anything in your Global.ascx.cs file.

自定义 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));
    }
}

基本控制器类:

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
            };
    }
}

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

Now, on your controller action you can simply return something like so.

return Json(myObject, JsonRequestBehavior.AllowGet);

巴姆.你现在已经用 Json 返回了驼峰对象:)

BAM. You now have camelcase Objects returned with Json :)

注意:有多种方法可以通过对使用 Json 制作的每个对象的序列化程序设置来执行此操作.但是谁会在每次想要返回 Json 时都输入它?

NOTE: There are ways to do this with Serializer settings on each object that you make with Json. But who would want to type that out every time you want to return Json?

这篇关于MVC 4 中正确的 JSON 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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