Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you register the KotlinModule to the AWS lambda Jackson Object Mapper?

I'm using Kotlin to write an AWS Lambda. I have a Kotlin data class

class MessageObject(
  val id: String,
  val name: String,
  val otherId: String
)

This data class is used as the input to the required interface implementation

class Handler : RequestHandler<MessageObject, Output> {
  ...  
  override fun handleRequest(msg: MessageObject, ctx: Context) {
    ...
  }
}

When I test this lambda in the aws console, and pass it a proper JSON message, I get this:

An error occurred during JSON parsing: java.lang.RuntimeException
java.lang.RuntimeException: An error occurred during JSON parsing
Caused by: java.io.UncheckedIOException: 
com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of 'com.mycode.MessageObject'(no Creators, like default construct, exist): 
cannot deserialize from Object value (no delegate- or property-based Creator)

I'm almost certain this is fixed by saying: ObjectMapper().registerModule(KotlinModule()) but in the world of AWS Lambda how do I edit the object mapper provided by AWS?

like image 819
dustinevan Avatar asked Mar 04 '20 05:03

dustinevan


1 Answers

If you haven't gotten it to work with KotlinModule, since the problem you're having is that Jackson requires a default empty constructor and you currently don't have one. You could just change your MessageObject as follows and it should work:

  data class MessageObject(
  var id: String = "",
  var name: String = "",
  var otherId: String = ""
)

I created this repo with a fully functional kotlin lambda template using the Serverless Framework. Have a look for some other tidbits you might need: https://github.com/crafton/sls-aws-lambda-kotlin-gradlekt

like image 116
Crafton Avatar answered Sep 18 '22 01:09

Crafton