C# MVC 4 中正确的 JSON 序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17244774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Proper JSON serialization in MVC 4
提问by Mario
I'd like to have JSON 'properly' serialized (camelCase), and the ability to change date formats if necessary.
我想对 JSON 进行“正确”序列化(camelCase),并在必要时能够更改日期格式。
For Web API it is very easy - in the Global.asax I execute the following code
对于 Web API,它非常简单 - 在 Global.asax 中我执行以下代码
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
This code, at the pipeline level, handles serialization the way I'd like.
这段代码在管道级别以我想要的方式处理序列化。
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:
我想在 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() }
};
It seems to execute fine but when I return JSON from a controller it is all PascalCased. A simple example of my action method:
它似乎执行得很好,但是当我从控制器返回 JSON 时,它都是 PascalCased。我的操作方法的一个简单示例:
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?
我这样做是错误的吗?知道如何在管道级别完成此操作吗?
采纳答案by technicallyjosh
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.
我建议使用 ServiceStack 或 Json.NET 之类的东西来处理 MVC 应用程序中的 Json 输出。但是,您可以轻松编写一个类并使用基类覆盖 Json 方法。请参阅下面的示例。
NOTE: With this, you do not need anything in your Global.ascx.cs file.
注意:有了这个,您的 Global.ascx.cs 文件中不需要任何内容。
Custom JsonDotNetResult class:
自定义 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));
}
}
Base Controller class:
基本控制器类:
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. You now have camelcase Objects returned with 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 制作的每个对象上的序列化程序设置来做到这一点。但是谁会在每次想要返回 Json 时都输入它呢?
回答by fcuesta
While Web API uses JSON.NET, MVC4 uses by default the JavaScriptSerializer, and I dont think it supports changing to Camel Case serialization. Check this: Setting the default JSON serializer in ASP.NET MVC
虽然 Web API 使用 JSON.NET,但 MVC4 默认使用 JavaScriptSerializer,我认为它不支持更改为 Camel Case 序列化。检查这个:Setting the default JSON serializer in ASP.NET MVC
My suggestion is that you create a custom JsonNetResult as described here Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?and change the last line to:
我的建议是您创建一个自定义的 JsonNetResult,如在 ASP.NET MVC 3 中使用 JSON.NET 作为默认 JSON 序列化器中所述 - 这可能吗?并将最后一行更改为:
var serializedObject = JsonConvert.SerializeObject(
Data,
Formatting.Indented,
new JsonSerializerSettings { MappingResolver = new CamelCaseMappingResolver() });
回答by Neel
Note that below information is for Asp .Net core
.Net team has recently announced that MVC now serializes JSON with camel case names by default.
.Net 团队最近宣布,MVC 现在默认使用驼峰命名法序列化 JSON。
With couple of lines below you would be able to enable this functionality:
通过下面几行,您将能够启用此功能:
services
.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.ContractResolver = new DefaultContractResolver());
I wrote little blog on the same which is here.
我写了一篇关于这里的小博客。
回答by Jared Beach
You can create a static method to return a ContentResultthat utilizes the NewtonSoft.Jsonlibrary to do the serialization similar to this:
您可以创建一个静态方法来返回一个ContentResult利用该NewtonSoft.Json库进行序列化的方法,类似于:
public static ContentResult CamelJson<TData>(TData response)
{
DefaultContractResolver resolver = new CamelCasePropertyNamesContractResolver();
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = resolver,
DateFormatHandling = DateFormatHandling.IsoDateFormat
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(response, settings),
ContentType = "application/json"
};
}
Example usage:
用法示例:
[HttpGet]
public ContentResult GetCamelCaseJsonData()
{
return ContentUtils.CamelJson(result);
}
The output will be camel-case.
输出将是驼峰式的。

