Returning camelCase JSON from ASP.NET Web API

Loving ASP.NET Web API but not loving the .NET-centric PascalCase JSON it produces?

// a .NET class like this...
public class Book
{
    public int NumberOfPages { get; set; }
    public string Author { get; set; }
}
// ... should be serialized into JSON like this
{
    "numberOfPages": 42,
    "author": "JK Rowling"
}

Luckily this is quite easy to fix with a custom formatter. I started with Henrik Nielsen’s custom Json.NET formatter and changed it slightly to use a camelCase resolver and also indent the JSON output (just for developers; we would turn this off once the app was deployed). You can grab the code here: https://gist.github.com/2012642

Then just swap out the default JSON formatter in your global.asax.cs:

var config = GlobalConfiguration.Configuration;

// Replace the default JsonFormatter with our custom one
var index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonCamelCaseFormatter();

7 thoughts on “Returning camelCase JSON from ASP.NET Web API

  1. I guess this changes the formatting for all JSON produced by .NET? Also for reglar controllers that return JsonResult? Is there a way to change this so this is only for web api? I have much legacy code that I don’t want to refactor at this point.

  2. Would be great if we could do this for regular mvc, but…
    JsonResult uses JavaScriptSerializer directly in MVC3.
    Don’t know if MVC4 allows us to change implementation.

  3. In the final ASP.NET MVC 4 this is supported natively:

    void ConfigureApi(HttpConfiguration config) {
    var index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
    config.Formatters[index] = new JsonMediaTypeFormatter {
    SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
    };
    }

Comments are closed.