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.


Comments
gravatar jim Monday, March 25, 2013
Verrrrry nice. Impedance matching!!
Jordy Monday, March 25, 2013
Would this also effect the incoming json that is posted to the (api)controller?
gravatar Scott Monday, March 25, 2013
@Jorday: Json.NET does a case-insensitive de-serialization, so putting/posting json with ISBN, isbn, Isbn, or isbN should all get the value into the incoming model parameter.
gravatar Brent Coney Monday, March 25, 2013
Thank you so much for this! I was just starting to google around because I was sick of transforming them each time. Thanks again!
gravatar Ashwin Monday, March 25, 2013
@Scott: I think ASP.Net MVC does a case-sensitive de-serialization, so it there a way to overcome that?
gravatar Scott Monday, March 25, 2013
@Ashwin: did you have an example? Some value provides are culture sensitive, but I believe they all use a case insensitive lookup (at least with form/route/query string data).
jignesh shah Wednesday, March 27, 2013
Nice tip..thanks scott
gravatar ARoz Thursday, March 28, 2013
Man this is such useful info, this has been bugging me for ages. Thanks Scott Your a legend
gravatar Nick Saturday, March 30, 2013
JSON.Net comes with Visual Studio 2012 or we need download it from NuGet ?
gravatar Scott Saturday, March 30, 2013
@Nick: It will come with the WebAPI NuGet package by default, so if you install WebAPI you'll have JSON.NET
gravatar avi jassra Saturday, March 30, 2013
Nice stuff ....
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!