Issue with replacing Java DTO classes with Kotlin Data classes

By default Jackson needs a parameterless constructor to deserialize JSON to a class - Kotlin data classes do not have one, so you need to add a Jackson module to handle this:

jackson-module-kotlin

Edit: I've read the source for io.vertx.core.json.Json class and it seems that both object mappers used by the class are stored in public static fields.

So to register jackson-module-kotlin you need to include this snippet in your application initialization code (or anywhere else really as long as it is executed before you attempt to deserialize any Kotlin data classes):

Json.mapper.registerModule(new KotlinModule())
Json.prettyMapper.registerModule(new KotlinModule()) 

In my case, I create kotlin class DTO instance in java for consuming RESTful Api. Now I have 2 solutions tested:

  1. Use parameterless constructor in data class.

The reference kotlin says:

On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.

So I have a DTO in kotlin like this:

    data class Dto (
        var id: Int?=null,
        var version: Int?=null, 
        var title: String?=null,
        var firstname: String?=null,
        var lastname: String?=null,
        var birthdate: String?=null

)

Then, I create class instance DTO in java:

Dto dto = new Dto();
dto.setId(javadto.getId());
...
  1. Use plugin jackson-module-kotlin

import com.fasterxml.jackson.annotation.JsonProperty

    data class Dto (
            @JsonProperty("id") var id: Int?,
            @JsonProperty("version") var version: Int?, 
            @JsonProperty("title") var title: String?,
            @JsonProperty("firstname") var firstname: String?,
            @JsonProperty("lastname") var lastname: String?,
            @JsonProperty("birthdate") var birthdate: String?,

    )

Then, I create class instance DTO in java:

Dto dto = new Dto(null, null, null, null, null, null);
dto.setId(javadto.getId());
...

Tags:

Java

Dto

Kotlin