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.12k stars 175 forks source link

Enhancing Type Safety in convertValue #757

Closed mohamedanees6 closed 2 months ago

mohamedanees6 commented 8 months ago

Use case

On calling mapper.convertValue(null, String::class.java), can we return a nullable type T instead of T through a wrapper? This will enhance type safety in Kotlin.

Describe the solution you'd like

Below code results in NPE,

   @Test
    fun test() {
        val kotlinModule = KotlinModule.Builder()
            .enable(KotlinFeature.StrictNullChecks)
            .build()
        val mapper = JsonMapper.builder()
            .addModule(kotlinModule)
            .build()
        val convertValue = mapper.convertValue(null, String::class.java)
        print(convertValue.toString())
    }

I've made this workaround, can we think of creating a wrapper function that can provide type-safety? Its safer to assume objects coming from Java to be nullable always, rather than throwing NPE.

  @Test
    fun testNullSafe() {
        val convertValue: String? = demoFunction("demo", String::class.java)
        Assertions.assertEquals(4, convertValue?.length ?: 0)
        val convertValueNull: String? = demoFunction(null, String::class.java)
        Assertions.assertEquals(0, convertValueNull?.length ?: 0)
    }

    private fun <T> demoFunction(input: String?, clzz: Class<T>): T? {
        val kotlinModule = KotlinModule.Builder()
            .enable(KotlinFeature.StrictNullChecks)
            .build()
        val mapper = JsonMapper.builder()
            .addModule(kotlinModule)
            .build()
        return mapper.convertValue(input, clzz)
    }

Describe alternatives you've considered

No response

Additional context

No response

k163377 commented 2 months ago

The KotlinModule provides a convertValue extension function. However, this function has the same problem as #399 .

So, it is closed as a duplicate of #399