I'm working with an old legacy project with interesting entity property naming. My task is to replace Nancy modules with MVC API Controllers. What I want to achieve here is to serialize the JSON response from controllers where only the first character in DTO property names are affected.
Here is my issue:
Example:
public class FooDto
{
public string INFooBar { get; set; }
}
This is serialized to:
{
"inFooBar": null
}
aspnet core 3.1 is using CamelCaseNaming strategy by default and this is totally correct serialization to camel case but what I want to achieve is (the system has a lot of consumers, so the serialization must not be changed):
{
"iNFooBar": null
}
The old Nancy endpoints are doing this somehow.
My work around is to override the DefaultNamingStrategy and explicitly lower case the first character in a Custom naming strategy:
public class CustomNamingStrategy : DefaultNamingStrategy
{
protected override string ResolvePropertyName(string name)
{
var pascalCasingName = base.ResolvePropertyName(name);
var firstCharacterLower = pascalCasingName.Substring(0, 1). ToLowerInvariant();
var result = $"{firstCharacterLower}{pascalCasingName.Remove(0, 1)}";
return result;
}
}
Startup.cs:
services.AddMvc()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CustomNamingStrategy()
};
});
My questions are:
- Is there any built-in support for this behaviour, that I have missed?
- Does anyone else have a more clever solution for this issue?