MVC 6 Camel Case JSON

I am excited with all the new features that are coming with MVC 6. One of the main differences between MVC 6 and previous versions is that it doesn't have two different libraries and controllers for MVC and Web API. 

The previous versions of Asp.Net MVC uses JavaScriptSerializer for MVC controllers and JSON.NET for Web API controllers.

This means, if you have an application which uses both MVC controllers and Web API controllers then you need to apply any custom JSON serialization configurations twice or you should replace JavaScriptSerializer with JSON.NET.

Asp.Net MVC 6 uses JSON.NET by default for JSON serialization and because it doesn't use two different controller base classes for MVC and Web API, we apply any custom JSON settings once that will be used by MVC and Web API.

We can apply these settings in ConfigureServices method when adding MVC service in the Startup class.

Here is an example how we can change JSON output formatter to use camel case

// Sample
 public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
			services.AddMvc()
					.Configure<MvcOptions>(options => {

						var jsonOutputFormatter = new JsonOutputFormatter();
						jsonOutputFormatter.SerializerSettings.ContractResolver =
							new CamelCasePropertyNamesContractResolver();
						options.OutputFormatters.Insert(0, jsonOutputFormatter);
					});
        }

        public void Configure(IApplicationBuilder app)
        {
			app.UseMvc();
				
        }
    }

In this example, I simply created JsonOutputFormatter with custom settings and added it as a first item in the output formatters list.

You can also achieve the same result by any of the following approaches

  1. replace all existing JSON formatter with new custom formatter
  2. update existing JSON formatter with custom settings

 I am just using the easiest approach in this case.

comments powered by Disqus