Web API serialize properties starting from lowercase letter

Andrei picture Andrei · Mar 2, 2014 · Viewed 30.6k times · Source

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?

Answer

Andrei picture Andrei · Mar 2, 2014

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.