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?
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);
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 by default serializes values in camelCase format.