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

Time:03-01

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related