Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading