Kotlin doesn't play nicely with Jackson if the property name contains "is"


#1

Hello

I am using kotlin 1.20 and jackson 2.9.0.

The following code snippet:

data class MyResponse(var isDirectory: String)

fun main(args: Array<String>) {
    val mapper = ObjectMapper().registerModule(KotlinModule())

    println( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(MyResponse("hello")))

}

prints out this output:
{ }

If i change the name of the property:

data class MyResponse(var directory: String)
fun main(args: Array<String>) {
    val mapper = ObjectMapper().registerModule(KotlinModule())

    println( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(MyResponse("hello")))

}

The output strangely becomes okay:

{
  "directory" : "hello"
}

Basically, if i remove the “is” prefix from the property, it is okay. It also doesn’t work with "isFile"
I am not sure whether it is with kotlin or with jackson, but something is definitely wrong here. :slight_smile:

Thanks for the help!


#2

Maybe try annotating it with @JvmName(“isDirectory”)

https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#handling-signature-clashes-with-jvmname

That way your identifier in your src code is like you want it to be and should work like you expect it.

var isDirectory : String will be compiled to getIsDirectory()/setIsDirectory() so jackson thinks the name of the property is isDirectory instead of just directory.


#3

Something like this should do the trick, I guess:

class MyResponse(directory: String){
val isDirectory : String
@JvmName(“isDirectory”) get() = field

init {
    isDirectory = directory
}

}


#4

Just annotate with @get:JsonProperty(“isDirectory”), e.g.:

data class MyResponse(@get:JsonProperty(“isDirectory”) val isDirectory: String)

See this example: https://github.com/bastman/learn-spring-kotlin/blob/master/src/main/kotlin/com/example/demo/api/echo/EchoController.kt

Hope this helps.


#5

Thank you!