https://kotlinlang.org logo
Title
r

Rodrigo Silva

02/27/2023, 10:02 PM
Hi all. Using KotlinX, how do I serialize or desarialize a generic attribute?
@Serializable
data class Test<T>(
val attr: T
)
r

Rodrigo Silva

02/28/2023, 12:52 PM
Thanks @Adam S But i have another question How do I serializer and deserializer this class
@Serializable(with = BoxSerializer::class)
data class Box<T>(
val name: String
val contents: T
)
Im lost here
override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
a

Adam S

02/28/2023, 12:55 PM
Generics can be really difficult with KxS, so I understand what you mean. What can
T
be? Do you have a class for it?
r

Rodrigo Silva

02/28/2023, 1:01 PM
I'm using a messenger system. The stream follows publish the command-> read the command
@Serializable
data class Command <T> (
 @Serializeble(KUUID::class) val id: UUID,
  val status: CommandStatusEnum,
   val message: T
)
enum class CommandStatusEnum(val value: String) {
  Open("Open"),
  Closed("Closed"),
  Processing("Processing"),
  Error("Error")
}
object KUUID : KSerializer<UUID> {
  override val descriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
  override fun serialize(encoder: Encoder, value: UUID) = encoder.encodeString(value.toString())
  override fun deserialize(decoder: Decoder): UUID = UUID.fromString(decoder.decodeString())
}
the message can be any class, such as pro example, email class
@Serializable
data class EmailModel(
  @Serializable(KUUID::class) override val id: UUID,
  val active: Boolean,
  val address: String,
  @Serializable(KUUID::class) val associateFK: UUID
)
a

Adam S

02/28/2023, 1:05 PM
are the messages in JSON?
Can you add a discriminator into the message types? It’s difficult for KxS to try and figure out how to decode something if it doesn’t know what the type is
@Serializable
data class Command <T> (
  val status: CommandStatusEnum,
  val messageType: MessageType,
  val message: T
)
r

Rodrigo Silva

02/28/2023, 1:38 PM
I will convert the objects to jsonObject,
my question, is, when I have a class, with more than one attribute, how does that line
override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
override fun deserialize(decoder: Decoder) = Command((string, enum,  dataSerializer.deserialize(decoder))