I managed to get it working using the following code:
.AddNewtonsoftJson(options => {
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});
However this makes MVC use Newtonsoft
rather than System.Text.JSON
which is faster, async and built in.
Looking at the naming policy options in System.Text.JSON
I could only find CamelCase. Is there any native support for snake case? What is a better way of achieving snake case JSON naming style?
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.
[JsonExtensionData] allows you to do is to serialize elements of a JSON document which does not have matching properties on the destination object to the dictionary which is decorated with the [JsonExtensionData] attribute.
Just slight modification in pfx code to remove the dependency on Newtonsoft Json.Net
.
String
extension method to convert the given string to SnakeCase
.
public static class StringUtils
{
public static string ToSnakeCase(this string str)
{
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
}
}
Then in our SnakeCaseNamingPolicy
we can do
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();
public override string ConvertName(string name)
{
// Conversion to other naming convention goes here. Like SnakeCase, KebabCase etc.
return name.ToSnakeCase();
}
}
The last step is to register our naming policy in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(
options => {
options.JsonSerializerOptions.PropertyNamingPolicy =
SnakeCaseNamingPolicy.Instance;
});
}
Using the model:
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureCelcius { get; set; }
public int TemperatureFahrenheit { get; set; }
public string Summary { get; set; }
}
Json
output:
{
"date": "2019-10-28T08:26:14.878444+05:00",
"temperature_celcius": 4,
"temperature_fahrenheit": 0,
"summary": "Scorching"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With