TKIT_dev

Automatic WebAPI property casing serialization

April 10, 2015

If you work a lot with WebAPI’s and JavaScript and would like to follow the convention of lowerCamelCasing your JSON and UpperCamelCasing your .net model properties, you can do that by using Newtonsoft.Json CamelCasePropertyNamesContractResolver. This works for both directions “WebAPI -> client” and “client -> WebAPI” so that’s cool as well. You should simply set this up in your Global.asax and you’re good to go.

// Global.asax.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace YourApp.WebAPI
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            SetupJsonCasingFormatter();
        }

        private static void SetupJsonCasingFormatter()
        {
            var jsonFormatterSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
            jsonFormatterSettings.Formatting = Formatting.Indented;
            jsonFormatterSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}

Written by Tihomir Kit, a senior software engineer @Dovetail.
🖖 Stay curious. @GitHub