如何将传入的 AWS Lambda 请求反序列化为 lombok @Value 或 @Data 类?
如果我有一个
import lombok.Value;
@Value
public class IncomingRequest {
String data;
}
并尝试拥有一个 RequestHandler
,就像
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaHandler implements RequestHandler<IncomingRequest, String> {
@Override
public String handleRequest(IncomingRequest request, Context context) {
...
}
}
我只得到空的 request
对象或使用其他一些配置一样,我会得到反序列化异常。
我需要做什么才能使 AWS Lambda 正确反序列化到我的自定义类中?
If I have a
import lombok.Value;
@Value
public class IncomingRequest {
String data;
}
and try to have a RequestHandler
like
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaHandler implements RequestHandler<IncomingRequest, String> {
@Override
public String handleRequest(IncomingRequest request, Context context) {
...
}
}
I only ever get empty request
objects or with some other configuration I get deserialization exceptions.
What do I need to do to enable AWS Lambda to properly deserialize into my custom class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AWS Lambda 使用 Jackson 反序列化数据,因此需要一个无参数构造函数和属性设置器。您可以将这些设置器公开,但此时您有一个可变类,并且您通常不希望将其用于纯数据类。 “幸运的是”杰克逊无论如何都使用反射,因此可以(并且确实)访问私有方法。因此,您可以使用 @Value 而不是
@Value
这样,Jackson 就可以正确解析传入的 JSON,并且您的类仍然是不可变的。显然,如果您愿意,只要确保无参数构造函数仍然存在,您就可以通过注释向该类添加更多构造函数。如果您愿意,您也可以安全地添加
@ToString @EqualsAndHashCode
。AWS Lambda uses Jackson to deserialize the data and as such needs a no-arg constructor and setters for the properties. You could make those setters public but at that point you have a mutable class and you generally do not want that for pure data classes. "Luckily" Jackson uses reflection anyway and therefore can (and does) access private methods. Instead of
@Value
you can therefore useThat way Jackson can properly parse the incoming JSON and your class remains sort-of immutable. Obviously you can add more constructors via annotation to that class if you want to as long as you make sure a no-args constructor is also still present. Add you can safely add
@ToString @EqualsAndHashCode
as well if you want to.您可以在
IncomingRequest
上使用@Jacksonized @Builder
。 Jackson 将使用该构建器来创建实例,并且您的类将保持不可变。You can use a
@Jacksonized @Builder
onIncomingRequest
. Jackson will use that builder to create instances, and your class will remain immutable.