json - MVC JsonResult camelCase 序列化

标签 json asp.net-mvc asp.net-mvc-3 serialization camelcasing

我试图让我的操作返回一个 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/

相关文章:

json - 使用原始 tcp 时确保完整消息传递的好方法是什么?

json - 为什么我的订单数据没有保存在我的 json 文件中

c# - Ajax.BeginForm(), OnSuccess - 获取事件目标

javascript - 如何使用 JavaScript 中的索引浏览嵌套 JSON 文件?

python - json.loads() 返回一个 unicode 对象而不是一个字典

c# - 在没有回发的客户端过滤 Grid.Mvc

c# - 如何保存可以在 azure 友好的解决方案中的任何位置调用的单个变量?

asp.net-mvc - 显示时将部分字符串转换为 URL

asp.net - 无法使用 JQGrid 添加行

css - 编写非常大的级联样式表 (CSS) 文件的最佳方法是什么