我有一个lambda函数:
package org.smarter.note;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class AddNoteRequestHandler implements RequestHandler<NewNoteRequest, Note> {
private NoteRepository notes;
private LambdaLogger logger;
@Override
public Note handleRequest(NewNoteRequest newNote, Context context) {
init(context);
log("creating note: " + newNote.toJson());
notes.create(newNote);
return new Note();
}
private void log(String message) {
logger.log(String.format("%s\n", message));
}
private void init(Context context) {
this.logger = context.getLogger();
this.notes = new NoteRepository();
}
}
然后当我使用sam本地测试lambda时,发送请求:
{
"title": "hello",
"content": "body"
}
我期待json自动转换为NewNoteRequest
,但它没有。这是日志:
You can now browse to the above endpoints to invoke your functions.
You do not need to restart/reload SAM CLI while working on your functions,
changes will be reflected instantly/automatically. You only need to restart
SAM CLI if you update your AWS SAM template.
2017/12/28 11:06:57 Invoking org.smarter.note.AddNoteRequestHandler (java8)
2017/12/28 11:06:57 Decompressing /Work/smarter-serverless/build/distributions/smarter-serverless.zip
2017/12/28 11:06:57 Mounting /private/var/folders/gv/m43y5g9x1xdc9f2kc2p0kpz00000gp/T/aws-sam-local-1514430417742696978 as /var/task:ro inside runtime container
START RequestId: bf0f77d3-198d-4211-ab9e-4c85a7c5de22 Version: $LATEST
creating note: {title=null, content=null}
我的山姆本地模板:
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
notes:
Type: AWS::Serverless::Function
Properties:
Handler: org.smarter.note.AddNoteRequestHandler
CodeUri: ./build/distributions/smarter-serverless.zip
Runtime: java8
Events:
PostEvent:
Type: Api
Properties:
Path: /notes
Method: post
POJO:
package org.smarter.note;
import com.amazonaws.services.dynamodbv2.document.Item;
import java.util.HashMap;
import java.util.Map;
class NewNoteRequest implements DynamoDBItem, Json {
private String title;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public Item item() {
return new Item()
.withString("title", this.title)
.withString("content", this.content);
}
@Override
public Map<String, Object> toJson() {
HashMap<String, Object> json = new HashMap<String, Object>();
json.put("title", this.title);
json.put("content", this.content);
return json;
}
}
依赖项也是:
dependencies {
compile(
"com.amazonaws:aws-lambda-java-core:1.1.0",
"com.amazonaws:aws-lambda-java-events:1.1.0"
)
}
我无法弄清楚哪个部分是错误的,AWS文档说它可以直接进行映射。请帮忙。
答案 0 :(得分:0)
我确实解决了这个问题的版本。在&#34;集成请求&#34;我有&#34; Access-Control-Allow-Credentials&#34;检查。取消选中它会导致POJO被填充。
答案 1 :(得分:0)
我有同样的问题。要解决此问题,我必须在相应的API网关配置中取消选择Lambda代理集成选项,然后将其部署到一个阶段。