1

I am trying to see how to go about inline types such as UShort, UInt in Kotlin and their deserialization using jackson.

build.gradle.kts

plugins {
    kotlin("jvm") version "1.8.10"
    kotlin("plugin.serialization") version "1.8.10"
}

group = "pl.demo"
java.sourceCompatibility = JavaVersion.VERSION_17

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.2")
    implementation(kotlin("reflect"))
    implementation(kotlin("stdlib"))
}

tasks {
    withType<KotlinCompile> {
        kotlinOptions {
            languageVersion = "1.8"
        }
    }
}

model.kts

data class Request(
    val counter: UShort
)

main.kts

fun main() {
    val mapper = jacksonObjectMapper()
    val json = mapper.writeValueAsString(
        Request(
            counter = 3u
        )
    )

    val request = mapper.readValue<Request>(json)
}

Which ends up yielding:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `pl.demo.Request` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"counter":3}"; line: 1, column: 2]

Is there something I am missing to make it work? I would ship that module as a library with sharable models consumed by different services as part of the contract but either I am missing something or those inline classes requires some custom deserializers which I believe should not be the case when using kotlin("plugin.serialization") which underneath have deserializers and serializers from those builtin types from sdk.

Any help would be more than welcomed :)

stosik
  • 43
  • 5
  • I am wondering: maybe the problem comes from immutability. Do you get the same error when either: 1. changing the `val counter` to `var counter` or 2. declaring json property explicitely: `@JsonProperty("counter") val counter` ? – amanin Apr 25 '23 at 07:00

0 Answers0