ASP.NET Web API – Returning javascript friendly (camelcase) json in two lines of code

By | May 26, 2016

Naming conventions of properties defer slightly in .NET and JavaScript. .NET uses pascal-case and JavaScript uses camel-case.

When developing a .NET API all the public properties should use the naming convention pascal-case. However if the service is consumed as an API with a JavaScript client then the json returned should be camel-case.

Now you could go and add the JsonPropertyAttribute (Newtonsoft.Json) and set the camel-case version of each property like the below code, however this would mean amending all of your dtos which are exposed. This could be a very time consuming task.

 public class Person 
    {
        [Required]
        [JsonProperty(PropertyName = "firstNames")]
        public string FirstNames { get; set; }

        [Required]
        [JsonProperty(PropertyName = "lastName")]
        public string LastName { get; set; }

        [JsonProperty(PropertyName = "dateOfBirth")]
        public DateTime? DateOfBirth { get; set; }
}

Or you can add the following two lines of code in the WebApiConfig.cs in the AppStart folder. Easy.

  var jsonSerializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
 jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

The WebApiConfig class may look like this

 public static class WebApiConfig
 {
   public static void Register(HttpConfiguration config)
   {
    var jsonSerializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
    jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    jsonSerializerSettings.Formatting = Formatting.Indented;
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
    );
  }
 }

Leave a Reply