Return a strongly typed object from your service, and it renders JSON properties as camelCase, because that's the default in ASP.NET Core MVC.
However, sometimes we need to create something on the fly using dynamic keyword and ExpandoObject class.
Those properties are not camelCased any more.
Howe to force ASP.NET Core MVC To cameCase everything?
Within your Startup.cs you can specify a resolver to use for serialisation. The one you are looking for is CamelCasePropertyNamesContractResolver and it can be enabled with the following:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
});
I have tested it with a dynamic type and it is working as expected.
On .NET 5 there is a specific flag to configure to serialize the dictionary keys
services.AddControllers()
.AddJsonOptions(o =>
o.JsonSerializerOptions.DictionaryKeyPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
);
More info
JsonSerializerOptions.DictionaryKeyPolicy Property
GitHub Issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With