How to exclude a null value computed in JsonValue from JSON serialized by Jackson?

143 Views Asked by At
class Wrapper(private val value: String?) {
    @JsonValue
    fun asValue(): String? {
        return value
    }
}    

val mapper = ObjectMapper()
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)


val item = mapOf(
               "first" to null,
               "second" to Wrapper(null),
               "third" to Wrapper("xyz")
           )

val str = mapper.writeValueAsString(item)

// -> {"second": null, "third": "xyz"}

Effectively both "first" and "second" fields contain null value. When the option Include.NON_NULL is enabled, I would expect that they are absent in the serialized representation. Nevertheless, the value returned from @JsonValue appears in the serialized JSON ("second" field).

How to exclude all null fields from the resulting JSON (whatever their origin is)?

0

There are 0 best solutions below