Replace the default Azure Function Json pascalCase formatter with camelCase
I use dotnet-isolated
function runtime and by default it is using ObjectSerializer
to convert objects to Json. The response is formatted with PascalCase
which is doesn't look as natural Json naming style. Let's see how we can format it to camelCase
and remove nullables.
{
"Errors": []
}
I didnt find a way how to configure the serializer for the function on global level, however it quite simple to set the serilizer while writing the response.
The following code example creates a new response and writes an object
var response = req.CreateResponse(HttpStatusCode.Created);
await response.WriteAsJsonAsync(new MyClass());
First, ObjectSerializer
is one of the optional parameters for the WriteAsJsonAsync
extension method, which can be replaced with one from Newtonsoft.Net
. ObjectSerializer
is part of Azure.Core.Serialization to user its Newtonsoft.Net
implementation, you have to install Microsoft.Azure.Core.NewtonsoftJson
package.
Secondly, you need to create settings for JsonSerializer:
var s = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var serializer = new NewtonsoftJsonObjectSerializer(s);
And the last one, use defined serializer while writing the response
await response.WriteAsJsonAsync(new MyClass(), serializer);
The response is formatted with camelCase
{
"errors": []
}
🚀 Turbocharge Your Infrastructure with Our Terraform Template Kits! 🚀
🌟 Slash deployment time and costs! Discover the ultimate solution for efficient, cost-effective cloud infrastructure. Perfect for DevOps enthusiasts looking for a reliable, scalable setup. Click here to revolutionize your workflow!
Learn More about Starter Terraform Kits for AKS,EKS and GKE
No comments are allowed for this post