asp.net-mvc - 如何从ASP.NET MVC控制器方法返回JSON.NET序列化的camelCase JSON?

我的问题是,我希望通过ASP.NET MVC Controller方法中的ActionResults返回camelcased(而不是标准的pascalcase)json数据,该方法由JSON.NET序列化。
例如,考虑以下C类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

默认情况下,当从MVC控制器中将此类的实例作为JSON返回时,它将按以下方式序列化:
{
  "FirstName": "Joe",
  "LastName": "Public"
}

我希望它(通过json.net)序列化为:
{
  "firstName": "Joe",
  "lastName": "Public"
}

我该怎么做?


最佳答案:

或者,简单地说:

JsonConvert.SerializeObject(
    <YOUR OBJECT>, 
    new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

例如:
return new ContentResult
{
    ContentType = "application/json",
    Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
    ContentEncoding = Encoding.UTF8
};

评论