How to return JSON result in camel-case format from ASP.NET Web API 2 Controller?
ASP.NET Web API V1 & V2 both return response in pascal-case format out of the box. Developers would like to change this if they would like to support mobile or JavaScript clients. The goal of this post is to explain how to return JSON result in camel-case format from ASP.NET Web API 2 controller.
I’ve got a ASP.NET Web API V2 application opened in Visual Studio 2015. Similar setting is also possible for Web API V1. If you are interested to find out similar concept for ASP.NET MVC Controllers that you can read my another post.
Following is the WebApiConfig class in WebApiConfig.cs file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Remove the XM Formatter from the web api
config.Formatters.Remove(config.Formatters.XmlFormatter);
// setup camel-case for property names
var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Let’s understand the code highlighted above:
- On line no. 8, we get the serializer settings of JSON formatter as this is where we would like to instruct for customization.
- Adding indentation formatting is optional that is shown on line no. 9.
- The important statement is on line no. 10, that sets the serializer settings resolver to
CamelCasePropertyNamesContractResolver. This resolver basically resolves member mappings for a type, camel casing property names. This `ContractResolver` is then used by the serializer when serializing .NET objects to JSON and vice versa.
So, just to illustrate, the output of a GET HTTP action for a resource named `Product` will look like this:
{
"id": 6,
"categoryId": 1,
"name": "Samsung S6 edge plus",
"description": "This is Samsung S6 edge plus smartphone.",
"imageUrl": "http://www.samsung.com/global/galaxy/galaxys6/galaxy-s6-edge/images/galaxy-s6-edge_gallery_front_black.png",
"cost": 650.0,
"outOfStock": false
}
Hope this post helps you to learn how to return JSON result in camel-case format from ASP.NET Web API 2 controller.
