~Has anyone managed to make `@JsonValue` work when...
# jackson-kotlin
r
Has anyone managed to make
@JsonValue
work when the property is nullable and the json has null as the value?
Edit - I wrongly thought this was a Kotlin issue but I can't make it work in Java either so moving to https://gitter.im/FasterXML/jackson-databind?at=635675f89ee3ec22b4d9a239
😶 1
Take the following:
Copy code
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.kotlin.kotlinModule
import org.intellij.lang.annotations.Language

data class Wrapper(val value: String, val inlined: Inlined)

data class Inlined(@get:JsonValue val inlined: Int?)

val objectMapper: JsonMapper = JsonMapper.builder()
        .addModule(kotlinModule())
        .build()

fun main() {
    checkSerializeDeserialize(Wrapper("whatever", Inlined(1))) // works
    checkSerializeDeserialize(Wrapper("whatever", Inlined(null))) // fails
}

private fun checkSerializeDeserialize(original: Wrapper) {
    val json = objectMapper.writeValueAsString(original)
    assert(json == """{"value":"whatever","inlined":${original.inlined.inlined}}""")

    val remade = objectMapper.readValue(json, Wrapper::class.java)
    assert(remade == original)
}
As commented, it works fine if the json contains
"inlined":1
, but while it will serialise
"inlined":null
correctly, it fails on deserialisation:
Copy code
Exception in thread "main" com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class pages.Wrapper] value failed for JSON property inlined due to missing (therefore NULL) value for creator parameter inlined which is a non-nullable type
 at [Source: (String)"{"value":"whatever","inlined":null}"; line: 1, column: 35] (through reference chain: pages.Wrapper["inlined"])
Hmm... this maybe "NOT KOTLIN". I can't get it to work in Java now either... could before I added a second property to
Wrapper
.
It's not pretty but this works:
Copy code
data class Wrapper(val value: String, val inlined: Inlined) {
    @JsonCreator
    private constructor(
        @JsonProperty("value") value: String, 
        @JsonProperty("inlined") inlined: Int?,
    ): this(value, Inlined(inlined))
}
580 Views