Lowercase JSON Attributes in C# API Responses
By FoxLearn 1/9/2025 3:23:52 AM 61
One standard approach is using the JsonPropertyName attribute, which allows you to specify the output for each field on an individual basis:
For example, Using JsonPropertyName
:
using System.Text.Json.Serialization; namespace MyCode { public class Response { [JsonPropertyName("orderId")] public int OrderID { get; set; } [JsonPropertyName("userName")] public string UserName { get; set; } } }
In this example, we are manually defining the JSON property names using JsonPropertyName
, which is useful when you need specific control over each property.
However, if you want a more scalable solution to apply a consistent naming convention across all properties in your response, you can use a global naming policy instead.
Note: The JsonPropertyName
attribute takes priority over the global naming policy. If you plan to use a global rule, make sure to remove these individual attributes from your model classes.
Create a Custom JsonNamingPolicy
using System.Text.Json; namespace MyCode { public class UppercaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { return name.ToUpper(); // This converts the property name to uppercase } } }
In this example, the custom UppercaseNamingPolicy
class overrides the ConvertName
method to return the property names in uppercase.
Apply the Naming Policy Globally
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = new UppercaseNamingPolicy(); });
By configuring .AddJsonOptions()
inside AddControllers()
, the UppercaseNamingPolicy
will be applied globally, ensuring that all property names in the JSON response are uppercase.
What if I want to use PascalCase instead?
.NET also offers built-in JsonNamingPolicy
for PascalCase
, so you don't need to implement it yourself:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.PascalCase; });
In .NET 8, built-in support is available for several naming conventions, including CamelCase (camelCase
), KebabCase (both lowercase kebab-case
and uppercase KEBAB-CASE
), and SnakeCase (both lowercase snake_case
and uppercase SNAKE_CASE
).
This provides a flexible and efficient way to enforce consistent naming conventions globally across your API responses without the need to manually annotate each field.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#