Reputation: 115
We are currently getting an AWS lambda response like this:
"{\"retailers\":[{\"address\":\"a\",\"retailerId\":1},
{\"address\":\"b\",\"retailerId\":2}]
,\"status\":{\"code\":200,\"type\":\"OK\",\"message\":\"Success\"}}"
The response is converting to json at the API Gateway using a code snippet:
$util.escapeJavaScript("$input.path('$')").replaceAll("\\","")
How we can directly make a json output from lambda function and serve as response body with out using the escapeJavaScript
function?
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;
}
}
Upvotes: 2
Views: 7276
Reputation: 33759
By providing POJOs as generic input and output parameters to you RequestHandler
implementation, AWS Lambda will take care of the serialization and deserialization between JSON and Java for you. The example below is copied from the Example 1: Creating Handler with Custom POJO Input/Output (Leverage the RequestHandler Interface) in the AWS Lambda developer guide:
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);
}
}
For example, if the event data in the Request object is:
{
"firstName":"value1",
"lastName" : "value2"
}
The method returns a Response object as follows:
{
"greetings": "Hello value1 value2."
}
Please follow the link above to see full example including implementations of the Request
and Response
classes.
Upvotes: 4