How to deal with empty lists that defaults to null in Jackson and Kotlin
Most times using Jackson will be straightforward and we won’t have to fiddle, but in the case you need to deserialize a data class that can have empty lists in Kotlin you can run into a null assertion error.
Here’s a data class:
@JsonInclude(JsonInclude.Include.NON_NULL)
data class SomeDataClass(
val otherFieldA: String? = null
val someOtherDataClassList: List<SomeOtherDataClass> = arrayListOf()
)
Enter fullscreen mode Exit fullscreen mode
In the previous code we have a potential error if payload received is an empty list in the field someOtherDataClassList
The simplest to this, using Jackson 2.17 (most recent version to the date this article was written) was to declare the Jackson Kotlin Module manually, and instead of using ObjectMapper.registerKotlinModule(), use this:
object JacksonProvider{
private val kotlinModule = KotlinModule.Builder()
.configure(KotlinFeature.NullIsSameAsDefault,true)
.build()
val mapper: ObjectMapper = ObjectMapper()
.registerModule(kotlinModule)
...(your other configuration options)...
}
Enter fullscreen mode Exit fullscreen mode
And that’s it! now you have a working empty list that does not throws an error while using Jackson and Kotlin.
The needed dependency is:
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.+")
Enter fullscreen mode Exit fullscreen mode
Thank you for reading!
답글 남기기