How do I make JSON serialization use the same case as the object property?

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?

>Solution :

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

Leave a Reply