Jackson Kotlin ignore null values (setSerializationInclusion(JsonInclude.Include.NON_NULL) not working)

27 Views Asked by At

This is already asked once before: Kotlin - Jackson ignore null values. I want to ignore null values in the json and use the default value when it's null. However, I do not want to set fields as nullable like in the original post, because this value should not be null in my program logic, the nullable parsing is only reserved for older data version's compatibility.

Many answers online such as How to tell Jackson to ignore a field during serialization if its value is null? point to setSerializationInclusion(JsonInclude.Include.NON_NULL), but this does not seem to be working. I even tried setting the field to Include.NON_NULL, which also doesn't work. I have the following minimal reproducible example which throws NullPointerException: Parameter specified as non-null is null: method icu.samnyan.aqua.spring.TestA.setS, parameter <set-?> instead of being parsed correctly.

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.ObjectMapper

val JACKSON = ObjectMapper().apply {
    setSerializationInclusion(JsonInclude.Include.NON_NULL)
    setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
}


class TestA {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    var s: String = ""
}

fun main() {
    println(JACKSON.readValue("""{"s":null}""", TestA::class.java).toString())
}
0

There are 0 best solutions below