If you are creating DTO (Data Transfer Objects) in ASP.NET Web API, chances are, you are using Pascal Casing for the names of your Properties/Members according to C# conventions.
However, as you may already know, JSON uses a convention of Camel Casing.
So how do you solve this discrepancy between the 2 platforms when your DTOs are serialized into JSON by Web API?
Well, fortunately, Microsoft has provided a very easy solution to this!
You can simply add the following code to your WebApiConfig.cs file in the App_Start folder of your Web API project (or the Startup class in Project Katana):
//Convert Pascal casing of DTO objects to Camel Casing to be supported by JavaScript clients
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Now when you use Pascal Casing for your Properties in your DTOs, they will automatically be converted to Camel Case when Web API serializes your objects into JSON thereby matching the JSON naming convention!
How cool is that???
This is awesome! Thanks!
ReplyDelete