我们目前正在获得这样的AWS lambda响应:
"{\"retailers\":[{\"address\":\"a\",\"retailerId\":1},
{\"address\":\"b\",\"retailerId\":2}]
,\"status\":{\"code\":200,\"type\":\"OK\",\"message\":\"Success\"}}"
响应是使用代码片段在API网关转换为json:
$util.escapeJavaScript("$input.path('$')").replaceAll("\\","")
我们如何直接从lambda函数生成json输出并作为响应体使用escapeJavaScript
函数?
public class GetRetailerInfo implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
try{
JSONObject parameters=new JSONObject(input.toString());
return APIUtil.getretailer(parameters,context).toString();
}
catch(Exception e){
e.printStackTrace();
}
return "Unable to process the request. "+input;
}
}
答案 0 :(得分:1)
通过将POJO作为通用输入和输出参数提供给您RequestHandler
,AWS Lambda将为您处理JSON和Java之间的序列化和反序列化。以下示例是从AWS Lambda开发人员指南中的Example 1: Creating Handler with Custom POJO Input/Output (Leverage the RequestHandler Interface)复制的:
package example;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.Context;
public class Hello implements RequestHandler<Request, Response> {
public Response handleRequest(Request request, Context context) {
String greetingString = String.format("Hello %s %s.", request.firstName, request.lastName);
return new Response(greetingString);
}
}
例如,如果Request对象中的事件数据是:
{
"firstName":"value1",
"lastName" : "value2"
}
该方法返回一个Response对象,如下所示:
{
"greetings": "Hello value1 value2."
}
请点击上面的链接查看完整示例,包括Request
和Response
类的实施。