我怎样才能返回由ASP.NET MVC控制器方法的JSON.NET序列化的camelCase JSON?

我的问题是,我希望从ASP.NET MVC控制器方法通过ActionResult s返回camelCased(而不是标准的PascalCase)JSON数据,由JSON.NET序列化。

作为一个例子,考虑下面的C#类:

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

默认情况下,当从MVC控制器以JSON的forms返回此类的实例时,将按以下方式进行序列化:

 { "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 }; 

我在Mats Karlsson的博客上find了一个很好的解决scheme。 解决scheme是编写一个ActionResult的子类,通过JSON.NET序列化数据,configuration后者遵循camelCase约定:

 public class JsonCamelCaseResult : ActionResult { public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior) { Data = data; JsonRequestBehavior = jsonRequestBehavior; } public Encoding ContentEncoding { get; set; } public string ContentType { get; set; } public object Data { get; set; } public JsonRequestBehavior JsonRequestBehavior { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data == null) return; var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings)); } } 

然后在你的MVC控制器方法中使用这个类如下:

 public ActionResult GetPerson() { return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)}; } 

对于WebAPI ,请查看此链接: http : //odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

基本上,将此代码添加到您的Application_Start

 var formatters = GlobalConfiguration.Configuration.Formatters; var jsonFormatter = formatters.JsonFormatter; var settings = jsonFormatter.SerializerSettings; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

我认为这是你正在寻找的简单答案。 这是来自Shawn Wildermuth的博客:

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

下面是一个action方法,它通过序列化一个对象数组来返回一个jsonstring(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实例作为第二个parameter passing。 这就是骆驼发生的原因。

在ASP.NET Core MVC中。

  public IActionResult Foo() { var data = GetData(); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return Json(data, settings); } 

自定义filter的替代方法是创build一个扩展方法来将任何对象序列化为JSON。

 public static class ObjectExtensions { /// <summary>Serializes the object to a JSON string.</summary> /// <returns>A JSON string representation of the object.</returns> public static string ToJson(this object value) { var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List<JsonConverter> { new StringEnumConverter() } }; return JsonConvert.SerializeObject(value, settings); } } 

然后在从控制器操作返回时调用它。

 return Content(person.ToJson(), "application/json");