-
-
Notifications
You must be signed in to change notification settings - Fork 182
Description
Hi! It seems that now ObjectMapper skips Nothing? properties:
// simplified example
// Jackson version I use is `2.10.3` (the latest stable patch version)
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.StdSerializer
class NothingData {
val data: Nothing? = null
}
@JsonSerialize(using = NothingDataWithSerializer.NothingDataSerializer::class)
class NothingDataWithSerializer {
val data: Nothing? = null
class NothingDataSerializer @JvmOverloads constructor(t: Class<NothingDataWithSerializer>? = null) : StdSerializer<NothingDataWithSerializer>(t) {
override fun serialize(value: NothingDataWithSerializer, generator: JsonGenerator, provider: SerializerProvider) {
generator.writeStartObject()
generator.writeObjectField("data", null)
generator.writeEndObject()
}
}
}
class IntData {
val data: Int? = null
}
fun main() {
val mapper = ObjectMapper()
println(mapper.writeValueAsString(NothingData())) // {}
println(mapper.writeValueAsString(NothingDataWithSerializer())) // {"data":null}
println(mapper.writeValueAsString(IntData())) // {"data":null}
}As you see, if type is other than Nothing? (like Int), data property is serialized properly.
Also, I've found out that I can define my own serializer which gives me behavior I want so I'm using this solution now.
Already asked that here but there is still no answer: https://stackoverflow.com/questions/60900202/serialize-nothing-property-via-jackson.
I've done a short debug and I see that in the first case Jackson sees that the type of the getter is java.lang.Void so this getter isn't added to properties. So the class has zero properties – that's what Jackson thinks.
Actually, Nothing? can contain only null, so it's easy to serialize it. For example, like in my custom serializer, as an object which is null.
Not sure where I should report it: here or in https://github.com/FasterXML/jackson-module-kotlin. If I do ObjectMapper().registerModule(KotlinModule()), there is the same behavior.
So I propose to implement this behavior and make by default...