Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

C# Lowercase all JSON attributes in your API responses

$
0
0

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:


Viewing all articles
Browse latest Browse all 285

Trending Articles