At the moment there's no builtin support for snake case,
but .NET Core 3.0 allows to set up a custom naming policy by inheriting from JsonNamingPolicy.
You need to implement the ConvertName method with the snake case conversion.
(Newtonsoft Json.NET has an internal StringUtils class which shows how to handle this.)
The POC implementation below, re-uses Json.NET's SnakeCaseNamingStrategy only for the snake case conversion (, whereas the whole application uses System.Text.Json).
It is better to avoid having a dependency on Newtonsoft Json.Net for only the snake case conversion, but in this rather LAZY example below I don't want to rethink/reinvent a snake case conversion method.
The main point of this answer is how to hook a custom policy (and not the snake case conversion itself.) (There are many libraries and code samples that show how to do so.)
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();
public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();
public override string ConvertName(string name)
{
/* A conversion to snake case implementation goes here. */
return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
}
}
In Startup.cs you apply this custom SnakeCaseNamingPolicy.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(
options => {
options.JsonSerializerOptions.PropertyNamingPolicy =
SnakeCaseNamingPolicy.Instance;
});
}
An instance of the class below
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureCelcius { get; set; }
public int TemperatureFahrenheit { get; set; }
[JsonPropertyName("Description")]
public string Summary { get; set; }
}
will have a Json representation as:
{ "date" : "2019-10-28T01:00:56.6498885+01:00",
"temperature_celcius" : 48,
"temperature_fahrenheit" : 118,
"Description" : "Cool"
}
Note that the property Summary has been given the name Description,
which matches its System.Text.Json.Serialization.JsonPropertyNameAttribute.