I am using Kotlin Springboot stack and in a rest controller we have a request body model with field "isAgent" which is boolean.
The ask is to fail if the request is not having this boolean field.
We checked that, if we annotate @JsonProperty(required = true) over the field. Jackson fails saying required parameter is not passed , which is inline with the ask. But when fields is passed with "" OR " " OR Null value , jackson defaults it to false , but we want to fail this.
Any Idea how to achieve this in SpringBott without implementing custom Deserializer.
You can define a custom ObjectMapper
bean setting DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES
to true
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
@Configuration
class JacksonConfig
@Bean
@Primary
fun objectMapper(): ObjectMapper {
return ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
}
}
Then a Request
class like below would fail deserialization if isUserAgent
is missing or null or blank
data class Request(
@JsonProperty(value = "isUserAgent", required = true)
val userAgentSpecified: Boolean,
)
Tests verifying the deserialization can be found on github