When creating an API in C#, you can control how your JSON response should be formatted. The classic way is to us the JsonPropertyName attribute and define the output in a per-field manner:
using System.Text.Json.Serialization;
namespace MyCode
{
public class Response
{
[JsonPropertyName("id")]
public int ID {get; set;}
[JsonPropertyName("customerId")]
public long CustomerID { get; set; }
}
}
But you can also define a JsonNamingPolicy global rule that will work for all of your fields at once.
Please note that the JsonPropertyName attribute will overrule the JsonNamingPolicy, so remove all attributes from your response model classes first.
STEP 1: CREATE A JsonNamingPolicy
using System.Text.Json;
using System.Text;
namespace MyCode
{
public class LowercaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return name.ToLower();
}
}
}
The JsonNamingPolicy contains one method, ConvertName. In my case, the code is simple, as I’m just lowercasing the property.
STEP 2: ADD THE NAMING POLICY AS A JSON OPTION TO THE AddControllers() METHOD
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = new LowercaseNamingPolicy();
}
);
Add .AddJsonOptions() to the AddControllers() method, and the JsonNamingPolicy will be called for each field in each response.
WHAT IF I WOULD LIKE TO USE camelCase INSTEAD?
The JsonNamingPolicy already have a built in version of camelCase, so no need for you to code that one from scratch.
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
}
);
In fact, when using .NET 8, there is built in support for CamelCase (camelCase), KebabCase lower and KebabCase upper (kebab-case and KEBAB-CASE) and SnakeCase lower/Snakecase upper (snake_case and SNAKE_CASE).
That’s it. Happy coding.
MORE TO READ:
- Snake Case VS Camel Case VS Pascal Case VS Kebab Case – What’s the Difference Between Casings? by Dionysia Lemonaki
- C# Newtonsoft camelCasing the serialized JSON output by briancaos
- ID or Id? Naming conventions in code by briancaos
- How to customize property names and values with System.Text.Json from Microsoft