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()
)
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)...
}
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.+")
Thank you for reading!
United States
NORTH AMERICA
Related News
๐ I Built a Dropshipping Automation Pipeline โ Here's What I Learned (and What I'd Do Differently)
10h ago
How I Cut My LLM API Bill by 40x: A Freelancer's Migration Story
10h ago

Mattress Firm Coupons: Save up to $600
3h ago
Google Ordered to Pay $2 Billion For Anti-Competitive Practices By Swedish Court
20h ago
The Censorship Wall: Why Every AI Companion App Ends Up Filtering You
20h ago