我试图让我的操作返回一个 JsonResult,它的所有属性都在 camelCase 中。
我有一个简单的模型:
public class MyModel
{
public int SomeInteger { get; set; }
public string SomeString { get; set; }
}
还有一个简单的 Controller Action :
public JsonResult Index()
{
MyModel model = new MyModel();
model.SomeInteger = 1;
model.SomeString = "SomeString";
return Json(model, JsonRequestBehavior.AllowGet);
}
现在调用此操作方法会返回一个包含以下数据的 JsonResult:
{"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 .它说:
要使用驼峰式大小写编写 JSON 属性名称,而不更改数据模型,请在序列化程序上设置 CamelCasePropertyNamesContractResolver:
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 以解决此问题。我试过了,但我不能让它工作。
你们知道我哪里做错了吗?
最佳答案
如果您想从您的操作中返回一个遵循驼峰表示法的 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);
}
关于json - MVC JsonResult camelCase 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040838/