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

Kogera should consider `data class` property defaults with `JsonInclude.Include.NON_DEFAULT`

Open Quantum64 opened this issue 1 year ago • 1 comments

This is a shortcoming in jackson-module-kotlin that I hoped could be fixed by this project.

Consider the mapper

val mapper = ObjectMapper()
        .registerKotlinModule()
        .setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)

and the class

data class TestData(
    val defaulted: Boolean = true
)

When we serialize TestData where defaulted = false with this mapper, the field is skipped since the mapper assumes that false is the default value for a boolean property. However, when the value is deserialized, the default value for the property is used, and this causes a roundtrip failure.

val data = TestData(defaulted = false)
println(data) // TestData(defaulted=false)
println(println(mapper.writeValueAsString(data))) // {}
println(mapper.readValue(mapper.writeValueAsString(data), TestData::class.java)) // TestData(defaulted=true)

Is there any way this new approach with kotlinx-metadata can be used to determine when a property's value matches the default constructor value and adjust serialization appropriately, or maybe just always include properties when the default is non-standard?

Here is the corresponding issue for jackson-module-kotlin: https://github.com/FasterXML/jackson-module-kotlin/issues/478

Quantum64 avatar Mar 17 '23 13:03 Quantum64

The concrete default values exist only on the bytecode and cannot be read or used for comparison. Thus, it is theoretically impossible to implement this correctly.

It is also difficult to include a default value in a property if it is specified in the factory. This is because it appears to be difficult to get the creator in this processing scope.

https://www.javadoc.io/doc/com.fasterxml.jackson.core/jackson-databind/latest/com/fasterxml/jackson/databind/AnnotationIntrospector.html#findPropertyInclusion-com.fasterxml.jackson.databind.introspect.Annotated-

k163377 avatar Mar 17 '23 17:03 k163377