Web API serialize properties starting from lowercase letter

C#.Netasp.net Mvcasp.net Web-Apijson.net

C# Problem Overview


How can I configure serialization of my Web API to use camelCase (starting from lowercase letter) property names instead of PascalCase like it is in C#.

Can I do it globally for the whole project?

C# Solutions


Solution 1 - C#

If you want to change serialization behavior in Newtonsoft.Json aka JSON.NET, you need to create your settings:

var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings 
{ 
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    NullValueHandling = NullValueHandling.Ignore // ignore null values
});

You can also pass these settings into JsonConvert.SerializeObject:

JsonConvert.SerializeObject(objectToSerialize, serializerSettings);

For ASP.NET MVC and Web API. In Global.asax:

protected void Application_Start()
{
   GlobalConfiguration.Configuration
	  .Formatters
	  .JsonFormatter
	  .SerializerSettings
	  .ContractResolver = new CamelCasePropertyNamesContractResolver();
}

Exclude null values:

GlobalConfiguration.Configuration
	.Formatters
	.JsonFormatter
	.SerializerSettings
	.NullValueHandling = NullValueHandling.Ignore;

Indicates that null values should not be included in resulting JSON.

ASP.NET Core

ASP.NET Core by default serializes values in camelCase format.

Solution 2 - C#

For MVC 6.0.0-rc1-final

Edit Startup.cs, In the ConfigureServices(IserviceCollection), modify services.AddMvc();

services.AddMvc(options =>
{
    var formatter = new JsonOutputFormatter
    {
        SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
    };
    options.OutputFormatters.Insert(0, formatter);
});

Solution 3 - C#

ASP.NET CORE 1.0.0 Json serializes have default camelCase. Referee this Announcement

Solution 4 - C#

If you want to do this in the newer (vNext) C# 6.0, then you have to configure this through MvcOptions in the ConfigureServices method located in the Startup.cs class file.

services.AddMvc().Configure<MvcOptions>(options =>
{
    var jsonOutputFormatter = new JsonOutputFormatter();
    jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    jsonOutputFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;

    options.OutputFormatters.Insert(0, jsonOutputFormatter);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreiView Question on Stackoverflow
Solution 1 - C#AndreiView Answer on Stackoverflow
Solution 2 - C#JonView Answer on Stackoverflow
Solution 3 - C#Ghanshyam JoshiView Answer on Stackoverflow
Solution 4 - C#VivendiView Answer on Stackoverflow