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

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

问题描述

我想有JSON'正确'的序列化(驼峰),如果需要更改日期格式的能力。

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

对于Web API是非常容易 - 在Global.asax我执行以下code

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();

这code,在管道的水平,处理系列化我喜欢的方式。

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

我想完成在MVC 4同样的事情 - 有任何JSON从控制器操作方法返回到正确序列化。随着一点点的搜索,我发现下面的code在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);

BAM。你现在有驼峰的对象使用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?

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

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