javaamazon-web-servicesaws-lambdajacksonlombok

How can I deserialize the incoming AWS Lambda request into a lombok @Value or @Data class?


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?


Solution

  • 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 use

    import lombok.AccessLevel;
    import lombok.Getter;
    import lombok.Setter;
    
    @Getter
    @Setter(AccessLevel.PRIVATE)
    public class IncomingRequest {
        String data;
    }
    

    That 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.