Polymorphic object serialization as another's field won't print type name :(

5 views
Skip to first unread message

Chuanwise Rafter

unread,
Sep 8, 2024, 9:08:29 PMSep 8
to jackson-user
There are some interfaces and its implementation data classes :

```kotlin
////////////////// 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:

```json
{
  "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:

```kotlin
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:

```json
{
  ...
  "subject" : {
    "id" : "subject-id"
  }
  ...
}
```

Why `type` field won't be printed when `subject` is a field? How to fix it?

Reply all
Reply to author
Forward
0 new messages