I have a class structure roughly like: ```sealed c...
# serialization
b
I have a class structure roughly like:
Copy code
sealed class MessagePayload ...

data class PayloadOne(val foo: String) : MessagePayload ...

class Message(val msgType: MessageType, val payload: MessagePayload) { ... }
and I was hoping to get it to serialize as:
Copy code
{
  "msgType": "payloadOne",
  "payload": {
    "foo": "..."
  }
}
that is: have the discriminant for the 'payload' field actually be at a layer "above", is that possible via just annotations? or would it require custom serializer/deserializer?
d
That json payload is possible with annotations but you'll have to change your class structure. Otherwise you have to write your own serializer.
b
oh, that'd be great if i could achieve it with annotations...i've been looking around at custom serializers and not feeling too encouraged. how would the class structure have to change?
d
Copy code
sealed class MessagePayload ...

data class PayloadOne(val foo: String) : MessagePayload ...

sealed class Message {
  abstract val msgType: MessageType
  abstract val payload: MessagePayload
}

data class PayloadOneMessage(override val msgType: MessageType, override val payload: PayloadOne) : Message()
b
ah, and then explicitly serialize as
PayloadOneMessage
and not
Message
, right?
d
Ehh, well if you want the discriminator then you have to use
Message
.
b
ok, i'll play around with that a bit. thanks!
this worked great, thank you!
i'm a bit confused, actually, why this doesn't serialize the
msgType
field? i end up with something like:
Copy code
{
  "type": "MyMsgType",
  "payload": {
    "foo": "hello"
  }
}
which is what i want, but why doesn't
msgType
get serialized there?
d
Not sure. I'd have to see code.
b
(trying to put a playground link together, but from what i can tell they don't have kotlinx serialization available there)
here's a playground with the code, even though it won't run there: https://pl.kotl.in/edW2zL-NX
hm, the
msgType
field is omitted from the tostring as well, for example:
Copy code
println(PayloadOneMessage(PayloadOne("hello")))
prints
PayloadOneMessage(payload=PayloadOne(foo=hello))
d
It's because you removed it from the ctor.
b
ahhhh, because it's a data class
d
Try adding a
@Required
annotation to the field.
b
yeah, that did it. for my case it works out because i don't actually want it, but wanted to understand why it wasn't there.