FasterXML / jackson-module-kotlin

Module that adds support for serialization/deserialization of Kotlin (http://kotlinlang.org) classes and data classes.
Apache License 2.0
1.11k stars 175 forks source link

Field proliferation bug when using ObjectMapper in Kotlin #772

Closed Yaklede closed 2 weeks ago

Yaklede commented 5 months ago

Search before asking

Describe the bug

Field proliferation bug when using ObjectMapper in Kotlin

Version Information

2.15.3

Reproduction

<-- Any of the following

  1. Brief code sample/snippet: include here in preformatted/code section
  2. Longer example stored somewhere else (diff repo, snippet), add a link
  3. Textual explanation: include here -->
    // Your code here

Here is the class information as follows.

data class MapperTest(
    @field:JsonProperty("tPhone")
    val tPhone: String,
    @field:JsonProperty("tData")
    val tData: String,
    @field:JsonProperty("tEmail")
    val tEmail: String,
)

If you convert using objectMapper to JSON in this state, it will look like this.

class ObjectMapperTest {
    private val objectMapper = ObjectMapper().registerKotlinModule().registerModules(JavaTimeModule())
    @Test
    fun test() {
        val request = MapperTest(
            tPhone = "phone",
            tData =  "data",
            tEmail =  "email"
        )
        val result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request)
        println(result)
    }
}
{
  "tPhone" : "phone",
  "tData" : "data",
  "tEmail" : "email",
  "tphone" : "phone",
  "tdata" : "data",
  "temail" : "email"
}

I have found where the issue lies.

I was able to find the issue within the collectAll() method in the POJOPropertiesCollector.class.

image

In the following state, when the _addMethods() method is called, the number of properties increases to six. image

In my opinion, the issue seems to arise from the discrepancy between the names of the getter methods and the fields during the process of decompiling the Kotlin code into Java code.

I hope this bug report is helpful.

Expected behavior

No response

Additional context

No response

cowtowncoder commented 5 months ago

Kotlin-related, will transfer to Kotlin module repo.

k163377 commented 2 weeks ago

It is closed as a duplicate of #630 A possible solution is to enable KotrinPropertyNameAsImplicitName.

.registerKotlinModule { enable(KotlinFeature.KotlinPropertyNameAsImplicitName) }