我的问题是,我希望返回camelcases(而不是标准PascalCase) JSON数据通过ActionResults从ASP。NET MVC控制器方法,由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
};

其他回答

我想这就是你想要的简单答案。这是Shawn Wildermuth的博客:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

我是这样做的:

public static class JsonExtension
{
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
        };
        return JsonConvert.SerializeObject(value, settings);
    }
}

这是MVC核心中一个简单的扩展方法,它会给你项目中的每个对象ToJson()能力,在我看来,在一个MVC项目中,大多数对象应该有成为json的能力,当然这取决于:)

如果你在。net core web api中返回ActionResult,或IHttpAction结果,那么你可以用Ok()方法包装你的模型,该方法将匹配你前端的情况并为你序列化它。不需要使用JsonConvert。:)

下面是一个动作方法,通过序列化一个对象数组返回一个json字符串(cameCase)。

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);
    }

注意作为第二个参数传递的JsonSerializerSettings实例。这就是骆驼案发生的原因。

将Json NamingStrategy属性添加到类定义中。

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] 公共阶层人 { public string FirstName {get;设置;} 公共字符串LastName {get;设置;} }