Home > Back-end >  How do I make JSON serialization use the same case as the object property?
How do I make JSON serialization use the same case as the object property?

Time:01-19

When I call any of my api functions that return JSON, it always alters the casing of the object's properties. This must be the default behavior as I haven't configured anything.

However, I'd prefer if it serialized my objects using the same casing that's present in the class, ie. no modification, just copy what's there.

So if I have:

public class Exercise
{
    public string ExerciseId { get; set; }
    public string ExerciseName { get; set; }
}

I'd like the properties to be serialized as ExerciseId and ExerciseName, not exerciseId and exerciseName.

The target framework is .NET 6.0. I haven't registered any middleware, I'm just adorning my classes with the [Serializable] attribute.

Here's an example of the JSON that is output:

{
   "exerciseId":"BBBC",
   "exerciseName":"Barbell Bicep Curl"
}

How do I configure that and is it possible to configure it in a single location and have it apply everywhere?

CodePudding user response:

To configure the default JSON serialization handler across all controllers / actions, set the naming policy via AddJsonOptions in your Program.cs.

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

This will maintain the casing utilized in your C# classes.

https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.propertynamingpolicy?view=net-6.0

CodePudding user response:

From How to customize property names and values with System.Text.Json doc:

Note
The web default is camel case.

If you want to switch from camel case to using property names then you need to change json options (note that for Minimal APIs you will need to configure JsonOptions from Microsoft.AspNetCore.Http.Json, see this answer):

builder.Services.AddControllers()
    .AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
  • Related