Error converting the Lambda event JSON payload to type System.String

Want to learn more about AWS Lambda and .NET? Check out my A Cloud Guru course on ASP.NET Web API and Lambda.

While working on the previous post, I was getting a couple of errors when trying to invoke one Lambda function from another.

I had a Lambda function that took a string as its input.

public Item FunctionHandler(string inventoryId, ILambdaContext context)
{ 
// snip...
}

I was calling the above function from another function using -

var request = new InvokeRequest
{
    FunctionName = "Inventory",
    Payload = "15"  
    // Payload = "15a" // alternate payload 
};

For the first payload I was getting -

“Error converting the Lambda event JSON payload to type System.String: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 3.”

For the second payload I was getting -

“Could not parse request body into json: Could not parse payload into json: Unexpected character (‘a’ (code 97)): Expected space separating root-level values at [Source: (byte[])“15a”; line: 1, column: 4]’”

I spent more than a few minutes working on it, and as with many things like this, the fix is very simple.

The fix

I should have serialized the payload in the request -

AmazonLambdaClient client = new AmazonLambdaClient();

var request = new InvokeRequest
{
    FunctionName = "Inventory",
    Payload = JsonSerializer.Serialize("15")
    //Payload = JsonSerializer.Serialize("15a") // alternate payload
};
var result = await client.InvokeAsync(request);
// snip...
comments powered by Disqus

Related