OdeToCode IC Logo

ASP.NET WebAPI Tip #3: camelCasing JSON

Monday, March 25, 2013

Let's say you have the following type definition in C#:

public class Thing
{
    public int Id { get; set; }
    public string FirstName { get; set; }    
    public string ISBN { get; set; }
    public DateTime ReleaseDate { get; set; }
}

The default JSON serialization of a thing will look like this:

{"Id":1,"FirstName":"Scott","ISBN":"123","ReleaseDate":"2013-03-24T16:26:33.7719981Z"}

It feels awkward to work with JavaScript objects where the first letter of a property name is a capital letter. But, it feels awkward to work with C# objects where the first letter of a property name is not capitalized.

Fortunately, the default serializer (Json.NET) will let you have the best of both worlds. All you need is a bit of configuration during application startup:

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

The CamelCasePropertyNamesContractResolver will produce the following JSON instead:

{
  "id": 1,
  "firstName": "Scott",
  "isbn": "123",
  "releaseDate": "2013-03-24T16:39:28.4516517Z"
}

We also tweaked the formatting settings to make the JSON easier for humans to read.