Use LocalDateTime in Micronaut Kotlin Data Class DTO

Viewed 1053

I got this DTO:

@Introspected
data class SomeDTO(
        val someLocalDateTime: LocalDateTime,
        val someString: String
)

And I want to use it in a Micronaut Controller like this:

@Post
@Status(HttpStatus.CREATED)
fun somePostCall(
    someDTO: SomeDTO,
    authentication: Authentication
) {
    this.someMethodCall(
            someDTO.someString,
            someDTO.someLocalDateTime,
            authentication.name
    )
}

I'm getting always this error:

Required argument [SomeDTO someDTO] not specified

I already tried to annotate the value in the DTO with @JsonFormat, @Format and with a custom TypeConverter (String to LocalDateTime) but none of them worked.

1 Answers

Try that ;-)

data class SomeDTO(
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
        val someLocalDateTime: LocalDateTime,
        val someString: String
)

If you would do it only for one class. Otherwise you could do it also on a global level.

public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class);
    }

    @Singleton
    static class ObjectMapperBeanEventListener implements BeanCreatedEventListener<ObjectMapper> {

        @Override
        public ObjectMapper onCreated(BeanCreatedEvent<ObjectMapper> event) {
            final ObjectMapper mapper = event.getBean();
            mapper.registerModule(new JavaTimeModule());
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            return mapper;
        }
    }
}
Related