ASP.NET Core 7 Web API - how to serialize in Pascal case?

198 views Asked by At

In Visual Studio 2022, and .NET 7, I created a new project with the template ASP.NET Core Web API. The template creates the WeatherForeCastController, which uses the WeatherForecast model. The properties of the model are in PascalCase:

public class WeatherForecast
{
    public DateOnly Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string? Summary { get; set; }
}

When I execute the API from Swagger, I get the properties in camelCase:

[
  {
    "date": "2023-11-28",
    "temperatureC": 53,
    "temperatureF": 127,
    "summary": "Hot"
  },
...
]

But I want to get them as they are defined in the .NET class. I added the following two statements in Program.cs right after

builder.Services.AddSwaggerGen();

builder.Services.ConfigureHttpJsonOptions(
    options => options.SerializerOptions.PropertyNamingPolicy = null);
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(
    options => options.SerializerOptions.PropertyNamingPolicy = null);

But I still get the JSON properties in camelCase.

How can I get the JSON properties in exactly the same case as defined in the .NET class, in this case Pascal case?

2

There are 2 answers

0
Shahar Shokrani On BEST ANSWER

Try to add it to AddControllers

builder.Services.AddControllers()
.AddJsonOptions(x =>
{
    x.JsonSerializerOptions.PropertyNamingPolicy = null;
});
1
Amit Mohanty On

You can use the JsonPropertyName attribute to specify the exact JSON property names.

public class WeatherForecast
{
    [JsonPropertyName("Date")]
    public DateOnly Date { get; set; }

    [JsonPropertyName("TemperatureC")]
    public int TemperatureC { get; set; }

    [JsonPropertyName("TemperatureF")]
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    [JsonPropertyName("Summary")]
    public string? Summary { get; set; }
}