There are some interfaces and its implementation data classes :
////////////////// Subject //////////////////
interface Subject
interface PluginSubject : Subject {
val id: String
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = TYPE_FIELD_NAME // "type"
)
abstract class AbstractSubject: Subject
@JsonTypeName(SUBJECT_TYPE_PLUGIN) // "plugin"
data class PluginSubjectImpl(
override val id: String
): AbstractSubject(), PluginSubject
////////////////// Packet //////////////////
interface RequestPacket : Packet {
// ...
val subject: Subject
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = TYPE_FIELD_NAME // "type"
)
abstract class AbstractPacket(
// ...
) : Packet
@JsonTypeName(PACKET_TYPE_REQUEST) // "request"
data class RequestPacketImpl(
// ...
override val subject: Subject
) : AbstractPacket(id, PACKET_TYPE_REQUEST, time), RequestPacket
I call mapper.writeValueAsString(PluginSubjectImpl("subject-id"))
and got:
{
"type" : "plugin",
"id" : "subject-id"
}
It’s good, type
field printed. Then I constructed an instance of RequestPacketImpl
then serialize it to make sure field type
also can be seen. My codes are:
val mapper = jacksonObjectMapper().apply {
enable(SerializationFeature.INDENT_OUTPUT)
}
val requestPacket: RequestPacket = RequestPacketImpl(
// ...
subject = PluginSubjectImpl("subject-id")
)
println(mapper.writeValueAsString(requestPacket))
assert(mapper.contentEqual(requestPacket, """
{
...
"subject": {
"type": "plugin",
"id": "subject-id"
}
...
}
""".trimIndent()))
Assertion failed, and it printed:
{
...
"subject" : {
"id" : "subject-id"
}
...
}
Why type
field won’t be printed when subject
is a field? How to fix it?