https://kotlinlang.org logo
#serialization
Title
# serialization
b

bbaldino

08/11/2022, 5:08 PM
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

Dominaezzz

08/11/2022, 7:30 PM
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

bbaldino

08/11/2022, 7:31 PM
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

Dominaezzz

08/11/2022, 7:35 PM
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

bbaldino

08/11/2022, 7:36 PM
ah, and then explicitly serialize as
PayloadOneMessage
and not
Message
, right?
d

Dominaezzz

08/11/2022, 7:37 PM
Ehh, well if you want the discriminator then you have to use
Message
.
b

bbaldino

08/11/2022, 7:37 PM
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

Dominaezzz

08/11/2022, 8:01 PM
Not sure. I'd have to see code.
b

bbaldino

08/11/2022, 8:01 PM
(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

Dominaezzz

08/11/2022, 8:43 PM
It's because you removed it from the ctor.
b

bbaldino

08/11/2022, 8:44 PM
ahhhh, because it's a data class
d

Dominaezzz

08/11/2022, 8:44 PM
Try adding a
@Required
annotation to the field.
b

bbaldino

08/11/2022, 8:45 PM
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.
4 Views