6

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!

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Terje Andersen
  • 429
  • 2
  • 17

2 Answers2

9

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

Terje Andersen
  • 429
  • 2
  • 17
  • 1
    For an individual field, you and also set `@JsonProperty(required = true)`, for those that come across this and have that scenario in mind. – gigaSproule Jul 28 '20 at 16:33
  • setting `@JsonProperty(required = true)` does NOT work if you have `@JsonTypeInfo` and are using polymorphism with jackson – Klimiuk S Feb 28 '22 at 10:17
0

Set your fields nullable like var param2: Boolean? = null and set

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Agnaramon
  • 851
  • 10
  • 15
  • That would work, but I don't want the property to be nullable. The use case behind this is an api taking orders, where the order class is also a jpa entity persisting the boolean property to the database, a non_null column in the end ... I want it to be set, both when creating the object via json, and via business logic – Terje Andersen Sep 13 '19 at 11:39
  • Oh okay ! I understand – Agnaramon Sep 13 '19 at 11:41