'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 1:[1]

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 can and does therefore 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.

Solution 2:[2]

You can use a @Jacksonized @Builder on IncomingRequest. Jackson will use that builder to create instances, and your class will remain immutable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jan Rieke