Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built in way of using snake case as the naming policy for JSON in ASP.NET Core 3?

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?

like image 264
numberjak Avatar asked Oct 26 '19 11:10

numberjak


People also ask

What is JSON Property C#?

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.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is JsonExtensionData?

[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.


1 Answers

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"
}
like image 116
Muhammad Hannan Avatar answered Oct 10 '22 06:10

Muhammad Hannan