How can I instruct Jackson to not automatically deserialize a kotlin.Boolean
parameter to false
if the serialized source (e.g. json object) does not contain the field?
See the current example:
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
data class Test(
var param1: String,
var param2: Boolean
)
fun main() {
val mapper = jacksonObjectMapper()
// passes, param2 is set to false, why isnt exception thrown?
val test1 = mapper.readValue("{\"param1\": \"bah\"}", Test::class.java)
// throws com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
val test2 = mapper.readValue("{\"param2\": true}", Test::class.java)
}
How can I make jackson complain with an exception in the first case where I don't give a value to the boolean parameter?
I am interested in this because I want my API to stop and complain if the client does not give a value to a Boolean parameter. I do not want it simply to be set to false when this happens.
Thanks!
Finally I found the answer myself by reading this issue of jackson-module-kotlin
: https://github.com/FasterXML/jackson-module-kotlin/issues/130
Apparently, kotlin's Boolean is an alias of the primitive.
And there is a jackson deserialization feature called FAIL_ON_NULL_FOR_PRIMITIVES
.
So in my case, the problem was fixed by calling objectMapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
Or for spring boot, the property spring.jackson.deserialization.FAIL_ON_NULL_FOR_PRIMITIVES=true