Search code examples
c#asp.net-coresystem.text.json

How to globally enforce lower case snake case on all serializing to JSON and also model binding


I have multiple models which I end up writing the JsonPropertyName attribute but this gets very annoying so I wanted to initialize it globally in program.cs. This was what I added thinking it would automatically handle the conversions:

builder.Services.AddControllers()
.AddJsonOptions(options =>
{
    // Global settings: use the defaults, but serialize enums as strings
    // (because it really should be the default)
    options.JsonSerializerOptions.Converters.Add(
        new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower, false));
});

However, in my models if I remove the attributes as shown here:

    [JsonPropertyName("state_id")]
    public required int StateId {get; set;}

    [JsonPropertyName("entity_name")]
    public required string EntityName {get; set;}

and forgo the JsonPropertyName I was under the assumption when serializing my model with Ok() to the frontend the names would automatically adjust to as my properties names once were (lowercase snake). However, they are still in camelCase and I am not sure why. Is there something additional I need to do?


Solution

  • The trouble is that you are not configuring the desired naming policy as the property naming policy for all options. Instead, you're currently registering an enum to string converter, which will only be used for enums, and specifying a naming policy for how that converter should transform enum member names to string valued json elements.

    To resolve the issue you need to specify the JsonSerializerOptions's PropertyNamingPolicy setting like so

    .AddJsonOptions(options =>
    {
       options.JsonSerializerOptions.PropertyNamingPoicy = 
           JsonNamingPolicy.SnakeCaseLower; 
    })
    

    Note you will still need to configure enum serialization if you wish their values to be serialized as snake case strings.

    See also the DictionaryKeyPolicy for which you may wish to specify snake case as well.