Since the default JSON serializer for AWS SDK .net serializes properties into PascalCase and I want camelCase, I created a custom serializer:
public class WellBehavedJsonSerializer: DefaultLambdaJsonSerializer {
public WellBehavedJsonSerializer() : base(CustomizeSerializer) { }
private static void CustomizeSerializer(JsonSerializerOptions options) {
options.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNameCaseInsensitive = true;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
}
}
I put this to the top of my Functions.cs:
[assembly: LambdaSerializer(typeof(WellBehavedJsonSerializer))]
But it is still serializing to PascalCase:
[
{
"Item": {
"ContainerID": "682b9bee-3ac4-4f8d-a768-b350e7a33b39",
"ItemID": "47147426-8948-4410-9486-196c6033f495",
"Name": "bar",
"Description": "",
"Taken": false,
"ReturnDue": "0001-01-01T00:00:00+00:00"
},
"Containers": [
{
"ContainerID": "682b9bee-3ac4-4f8d-a768-b350e7a33b39",
"Name": "foo",
"ParentContainerId": "00000000-0000-0000-0000-000000000000"
}
]
}
]
Is there anything else what I might be missing? Add some extra configuration to Startup.cs or the like?
Followup 1
There is a CamelCaseLambdaJsonSerializer but when I use this, I still get PascalCase.
Root cause
The reason it is not working as expected is because the .NET Lambda Annotations framework generates code for your Lambda function automatically in the background.
You can take a look at that auto-generated code at the following path.
In that auto-generated code, Lambda uses
System.Text.Json.JsonSerializer.Serializeirrespective of what you define in assembly attribute.What if you don't use Lambda Annotations framework
Now, let's talk about what if you don't use this framework, and write a normal Lambda function in .NET. You would use
APIGatewayProxyResponseobject to return the response.If you notice, here the body property is
string, and it's your responsibility to serialize the object in whatever case (Camel or Pascal).The chosen Lambda serializer will be applicable on the serialization of
APIGatewayProxyResponseobject, not on the internal body property.Notice, here the type of body is
string.Conclusion and Solution
But, as a workaround, you can always use
APIGatewayProxyResponseobject as return type in your function when working with Lambda Annotations Framework.This way, you'll have the following benefits.
bodyproperty.status codeandheaders.Note: In the above code
APIGatewayResponseManageris a self maintained wrapper class, not part of .NET SDK.