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

.NET Core中如何让AWS Lambda模拟工具解析JSON数组

解决AWS Lambda函数反序列化输入JSON为String类型的错误

错误原因

你遇到的Error deserializing the input JSON to type String错误,根本原因是Lambda处理程序的参数类型与测试请求格式不匹配:

  • 你的处理程序参数定义为string input,但测试工具传入的是完整的API Gateway请求JSON对象(包含body、path、httpMethod等字段)。
  • Lambda运行时尝试将整个JSON对象反序列化为string类型,自然会失败,和JSON中的数组无关。

解决方案

方案1:修改处理程序参数为API Gateway请求类型(推荐)

这是符合API Gateway触发Lambda实际场景的正确做法,使用APIGatewayHttpApiV2ProxyRequest作为参数,Lambda运行时会自动完成请求对象的反序列化:

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using System.Text.Json;
using System.Collections.Generic;

public class Function
{
    private readonly ILambdaLogger _log;

    public Function()
    {
        _log = LambdaLogger.Logger;
    }

    public async Task<APIGatewayHttpApiV2ProxyResponse> FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
    {
        _log.LogDebug($"Request Body: {request.Body}");

        // 将body反序列化为你的业务请求模型
        var requestModel = JsonSerializer.Deserialize<ClaimCountRequest>(request.Body);
        
        // 这里编写你的业务逻辑,比如计算ClaimsCount
        int claimsCount = 0; // 替换为实际逻辑

        return new APIGatewayHttpApiV2ProxyResponse
        {
            StatusCode = 200,
            Body = JsonSerializer.Serialize(new { ClaimsCount = claimsCount }),
            Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
        };
    }

    // 定义匹配请求body的业务模型
    public class ClaimCountRequest
    {
        public List<PolicyNumber> PolicyNumbers { get; set; }
        public string RenewalEffectiveDate { get; set; }
        public string State { get; set; }
    }

    public class PolicyNumber
    {
        public string Number { get; set; }
    }
}

修改后,你原来的测试请求格式可以直接使用,无需调整。

方案2:调整测试请求为纯字符串格式(不推荐)

如果坚持使用string input作为参数,需要将整个API Gateway请求JSON转义为字符串,作为测试工具的输入:

"{\"body\":\"{\\\"PolicyNumbers\\\":[{\\\"Number\\\":\\\"WCU9799P\\\"},{\\\"Number\\\":\\\"B1V48603\\\"}],\\\"RenewalEffectiveDate\\\":\\\"09/28/2016\\\",\\\"State\\\":\\\"\\\"}\",\"resource\":\"/{proxy+}\",\"path\":\"api/GetClaimsCount\",\"httpMethod\":\"POST\",\"headers\":{\"Accept\":\"application/json\",\"Accept-Encoding\":\"gzip, deflate, sdch\",\"Accept-Language\":\"en-US,en;q=0.8\"}}"

这种方式仅适用于测试,不符合实际生产环境中API Gateway触发Lambda的请求格式,因此不推荐。

补充说明

你之前的8个函数能正常运行,大概率是因为它们的测试请求是纯字符串,而非完整的API Gateway请求对象,或者实际部署后是通过其他方式触发(比如直接传递字符串参数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:05:23