jackson-module-kotlin icon indicating copy to clipboard operation
jackson-module-kotlin copied to clipboard

@JsonCreator does not always work with Kotlin

Open kostya-lnk-ms opened this issue 5 years ago • 0 comments

Describe the bug @JsonCreator does not seem to always work for Kotlin classes

To Reproduce

import com.fasterxml.jackson.annotation.JsonAutoDetect import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule

open class BaseClass(val a : Int, str: String)

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) class KotlinAdapter(aa: Int, str: String) :BaseClass(aa, str) { companion object { @JvmStatic @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) fun create(@JsonProperty("int prop", required = true) ip: Int, @JsonProperty("another", required = true) str: String) :BaseClass { return BaseClass(ip, str) } } }

fun main() { val om = ObjectMapper().registerKotlinModule() val t = om.readValue(""" { "int prop": 1, "another": "Hello" } """.trimIndent(), KotlinAdapter::class.java ) }

Throws Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid definition for property int prop (of type org.example.KotlinAdapter): Could not find creator property with name 'int prop' (known Creator properties: [aa, str]) at [Source: (String)"{ "int prop": 1, "another": "Hello" }"; line: 1, column: 1] at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:62) at com.fasterxml.jackson.databind.DeserializationContext.reportBadPropertyDefinition(DeserializationContext.java:1610)

Expected behavior It should deserialize using for properties specified by the @JsonCreator The above example, when a base class is defined in Java works.

Versions Kotlin: 1.4 Jackson-module-kotlin: 2.11.3 Jackson-databind: 2.11.3

Additional context The above example is an attempt to create a "view" class that maps properties of another class without the need to tune the ObjectMapper and change the original class

kostya-lnk-ms avatar Oct 14 '20 15:10 kostya-lnk-ms