3

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 Answers 2

7

Try to add it to AddControllers

builder.Services.AddControllers()
.AddJsonOptions(x =>
{
    x.JsonSerializerOptions.PropertyNamingPolicy = null;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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; }
}

1 Comment

Hey Alex, you can use Shahar Shokrani solution also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.