如何使用JavaScriptSerializer强制camelcase?

时间:2013-07-17 12:49:15

标签: c# asp.net-mvc asp.net-mvc-4

有可能吗?

我有一个这样的课程:

public class ABC
{
    [Key]
    [ScriptIgnore]
    public int Id { get; set; }

    public string Name { get; set; }

    public string AnotherField { get; set; }

    [ScriptIgnore]
    public virtual User User { get; set; }
}

但我希望像{ "name":"foo", "anotherField":"bar" }那样序列化而不是  { "Name":"foo", "AnotherField":"bar" }

这就是我的用法:

return Request.CreateResponse(HttpStatusCode.OK, new JavaScriptSerializer().Serialize(obj));

1 个答案:

答案 0 :(得分:-4)

您可以使用Newtonsoft.Json.Serialization的驼峰案例解析器; 在你的global.asax上,你在应用程序启动时注册它

using Newtonsoft.Json.Serialization;

protected void Application_Start()
{
     config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}