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!
In order to serialize and deserialize objects, we’ll need to have an instance of ObjectMapper for Kotlin. We can create one using jacksonObjectMapper (): Or we can create an ObjectMapper and then register KotlinModule: Now that we have our mapper, let’s use it to serialize a simple Movie object.
In this tutorial, we’ll discuss the Jackson support for Kotlin. We’ll explore how to serialize and deserialize both Object s and Collection s. We’ll also make use of @JsonProperty and @JsonInclude annotations.
A boolean type can be declared with the Boolean keyword and can only take the values true or false: Just like you have learned with other data types in the previous chapters, the example above can also be written without specifying the type, as Kotlin is smart enough to understand that the variables are Booleans:
As a matter of fact, when one of the required properties is missing in the JSON string, Jackson will fail to deserialize that JSON to the target Kotlin type. To represent this failure, it uses a special exception named MissingKotlinParameterException: As shown above, the exception describes the missing parameter using its parameter property.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With