Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to change the property names to snake_case in an ASP.NET Core 3.0 API?

I'm trying to change all the property names to snake_case globally in my ASP.NET Core 3.0 API, but I couldn't find a way.

Previously, in ASP.NET Core 2.2, I used:

services.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() })

Now in ASP Net Core 3.0 the only thing that I found barely similar was:

services.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase)

But snake_case is not present.

Is there a such way to make snake_case for the request and response objects globally in my ASP.NET Core 3.0 API?

like image 723
Diego Avatar asked Dec 06 '22 09:12

Diego


2 Answers

I found the solution after read https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio

The new code is:

.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() })
like image 170
Diego Avatar answered Mar 18 '23 15:03

Diego


For .NET Core 3.0, use:

 .AddJsonOptions(o => o.JsonSerializerOptions.PropertyNamingPolicy = null)
like image 35
rocky Avatar answered Mar 18 '23 16:03

rocky