You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda注解模式下自定义JSON序列化仍为PascalCase问题排查

解决AWS Lambda .NET JSON序列化始终为PascalCase的问题

核心排查与解决步骤:

  • 确认NuGet包与序列化器写法匹配:
    分两种核心序列化包场景,写法完全不同:

    • 若使用基于Newtonsoft.Json的Amazon.Lambda.Serialization.Json包,自定义序列化器需这么写:
      public class WellBehavedJsonSerializer : DefaultLambdaJsonSerializer
      {
          public WellBehavedJsonSerializer()
              : base(new JsonSerializerSettings
              {
                  ContractResolver = new CamelCasePropertyNamesContractResolver(),
                  NullValueHandling = NullValueHandling.Ignore // 可选配置
              })
          {
          }
      }
      
    • 若使用基于System.Text.Json的Amazon.Lambda.Serialization.SystemTextJson包,自定义序列化器要继承LambdaJsonSerializer:
      public class WellBehavedJsonSerializer : LambdaJsonSerializer
      {
          protected override void ConfigureJsonSerializerOptions(JsonSerializerOptions options)
          {
              options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
              options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; // 可选配置
          }
      }
      
  • 注解位置必须正确:
    [assembly: LambdaSerializer(typeof(WellBehavedJsonSerializer))] 必须放在命名空间声明之前,不能嵌套在类或命名空间内部,示例如下:

    [assembly: LambdaSerializer(typeof(WellBehavedJsonSerializer))]
    namespace YourLambdaProjectNamespace
    {
        public class Functions
        {
            // Lambda函数代码
        }
    }
    
  • 官方驼峰序列化器的命名空间注意:
    直接用CamelCaseLambdaJsonSerializer时,要对应正确的命名空间:

    • Newtonsoft.Json包对应:Amazon.Lambda.Serialization.Json.CamelCaseLambdaJsonSerializer
    • System.Text.Json包对应:Amazon.Lambda.Serialization.SystemTextJson.CamelCaseLambdaJsonSerializer
      要么在注解里写完整类型名,要么提前引入对应命名空间。
  • 排查部署配置的覆盖项:
    如果用Serverless Framework或CloudFormation部署,检查模板中的Function资源是否配置了RuntimeSerializer属性,这个配置会直接覆盖代码里的序列化器注解。

  • 清理重建项目:
    有时Visual Studio的缓存会导致代码变更未生效,先清理解决方案,重新生成后再部署Lambda函数。


内容的提问来源于stack exchange,提问作者rabejens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:12:13