MVC JsonResult camelCase 序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15040838/
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
MVC JsonResult camelCase serialization
提问by Thomas Mondel
I am trying to make my action return a JsonResult where all its properties are in camelCase.
我试图让我的操作返回一个 JsonResult,它的所有属性都在驼峰式大小写中。
I have a simply model:
我有一个简单的模型:
public class MyModel
{
public int SomeInteger { get; set; }
public string SomeString { get; set; }
}
And a simple controller action:
还有一个简单的控制器动作:
public JsonResult Index()
{
MyModel model = new MyModel();
model.SomeInteger = 1;
model.SomeString = "SomeString";
return Json(model, JsonRequestBehavior.AllowGet);
}
Calling this action method now returns a JsonResult containing the following data:
调用此操作方法现在返回包含以下数据的 JsonResult:
{"SomeInteger":1,"SomeString":"SomeString"}
For my uses i need the action return the data in camelCase, somehow like this:
对于我的用途,我需要该操作以驼峰格式返回数据,就像这样:
{"someInteger":1,"someString":"SomeString"}
Is there any elegant way to do this?
有没有什么优雅的方法来做到这一点?
I was looking into possible solutions around here and found MVC3 JSON Serialization: How to control the property names?where they set DataMember definitions to every property of the model, but I do not really want to do this.
我在这里寻找可能的解决方案,发现MVC3 JSON 序列化:如何控制属性名称?他们将 DataMember 定义设置为模型的每个属性,但我真的不想这样做。
Also I found a link where they say that it is possible to solve exactly this kind of issue: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing. It says:
我还找到了一个链接,他们说可以完全解决此类问题:http: //www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-序列化#json_camelcasing。它说:
To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:
要使用驼峰式大小写编写 JSON 属性名称,而不更改数据模型,请在序列化程序上设置 CamelCasePropertyNamesContractResolver:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
One entry on this blog http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/also mentiones this solution and states you can simply add it to the RouteConfig.RegisterRoutesto fix this issue. I tried it, but I couldn't make it work.
这个博客http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/上的一个条目也提到了这个解决方案,并指出你可以简单地将它添加到RouteConfig.RegisterRoutes来解决这个问题。我试过了,但我无法让它工作。
Do you guys have any idea where I was doing something wrong?
你们知道我哪里做错了吗?
采纳答案by Dresel
The Json functions of the Controller are just wrappers for creating JsonResults:
Controller 的 Json 函数只是用于创建 JsonResults 的包装器:
protected internal JsonResult Json(object data)
{
return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, string contentType)
{
return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
return Json(data, null /* contentType */, null /* contentEncoding */, behavior);
}
protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
{
return Json(data, contentType, null /* contentEncoding */, behavior);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
JsonResult internally uses JavaScriptSerializer, so you don't have control about the serialisation process:
JsonResult 内部使用 JavaScriptSerializer,因此您无法控制序列化过程:
public class JsonResult : ActionResult
{
public JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
/// <summary>
/// When set MaxJsonLength passed to the JavaScriptSerializer.
/// </summary>
public int? MaxJsonLength { get; set; }
/// <summary>
/// When set RecursionLimit passed to the JavaScriptSerializer.
/// </summary>
public int? RecursionLimit { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (MaxJsonLength.HasValue)
{
serializer.MaxJsonLength = MaxJsonLength.Value;
}
if (RecursionLimit.HasValue)
{
serializer.RecursionLimit = RecursionLimit.Value;
}
response.Write(serializer.Serialize(Data));
}
}
}
You have to create your own JsonResult and write your own Json Controller functions (if you need / want that). You can create new ones or overwrite existing ones, it is up to you. This linkmight also interest you.
您必须创建自己的 JsonResult 并编写自己的 Json 控制器函数(如果您需要/想要的话)。您可以创建新的或覆盖现有的,这取决于您。这种链接也可能会感兴趣。
回答by DanKodi
If you want to return a json string from your action which adheres to camelcase notation what you have to do is to create a JsonSerializerSettings instance and pass it as the second parameter of JsonConvert.SerializeObject(a,b) method.
如果您想从您的操作中返回一个遵循驼峰命名法的 json 字符串,您需要做的是创建一个 JsonSerializerSettings 实例并将其作为 JsonConvert.SerializeObject(a,b) 方法的第二个参数传递。
public string GetSerializedCourseVms()
{
var courses = new[]
{
new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
};
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
return JsonConvert.SerializeObject(courses, camelCaseFormatter);
}

