简体   繁体   中英

Deserialization exception accessing AWS Lambda Handler

I am starting with AWS Lambda. I have the following Java class created by using the Lambda run-time API:

public class HelloWorld1
    implements RequestHandler<Map<String, String>, String> {

    public String handleRequest(
        final Map<String, String> input,
        final Context context) {
        context.getLogger().log("Llamada: " + input);
        return "{\"HelloWorld\": \"" + input.get("key1") + "\"}";
    }
}

I do use the test feature of Lambda, using this "JSON Event" value:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

and it works fine.

But then I create an URL and try to use Postman to send a POST request to it, and it fails with an Internal Server Error. I am using the URL it was defined by AWS, I set the body to {"key1": "sjuan", "key2": "76"} , and I get in AWS CloudWatch a

An error occurred during JSON parsing: java.lang.RuntimeException
java.lang.RuntimeException: An error occurred during JSON parsing
Caused by: java.io.UncheckedIOException: com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token

What am I doing wrong?

If you want to be able to invoke an AWS Lambda function via a Rest call, use Amazon API Gateway. This is a service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at scale.

See this document that discusses how to develop an AWS Lambda function using the Java run-time API and then how to invoke it by using Amazon API Gateway:

Using Amazon API Gateway to invoke Lambda functions

When you invoke a Lambda function via the console you get to choose the input. The default is what you have in the question.

When you trigger a Lambda function via an event source like Amazon API Gateway the input is actually a JSON document that represents the entire HTTP request .

Java representations of these JSON objects can be found in the aws-lambda-java-events library.

So you handler method would look something like this instead:

public class ApiRequestHandler implements RequestHandler<APIGatewayV2HTTPEvent, APIGatewayV2HTTPResponse> {

    @Override
    public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) {
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM