I am trying to make my action return a JsonResult where all its properties are in camelCase.
我有一个简单的模型:
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:
{"SomeInteger":1,"SomeString":"SomeString"}
出于我的使用目的,我需要在camelCase中返回数据,某种程度上如下所示:
{"someInteger":1,"someString":"SomeString"}
有什么优雅的方法可以做到这一点吗?
我在这里寻找可能的解决方案,找到了MVC3 JSON Serialization: How to control the property names?个,他们在其中为模型的每个属性设置DataMember定义,但我真的不想这么做.
我还找到了一个链接,他们说完全有可能解决这类问题:http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing.上面写着:
To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
这个博客http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/上的一个条目也提到了这个解决方案,并表示你可以简单地将它添加到RouteConfig.RegisterRoutes中来解决这个问题.我试过了,但没能成功.
你们知道我哪里做错了什么吗?