Hi all. Using KotlinX, how do I serialize or desarialize a generic attribute? ```@Serializable data ...
r
Hi all. Using KotlinX, how do I serialize or desarialize a generic attribute?
Copy code
@Serializable
data class Test<T>(
val attr: T
)
r
Thanks @Adam S But i have another question How do I serializer and deserializer this class
Copy code
@Serializable(with = BoxSerializer::class)
data class Box<T>(
val name: String
val contents: T
)
Im lost here
Copy code
override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
a
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
I'm using a messenger system. The stream follows publish the command-> read the command
Copy code
@Serializable
data class Command <T> (
 @Serializeble(KUUID::class) val id: UUID,
  val status: CommandStatusEnum,
   val message: T
)
Copy code
enum class CommandStatusEnum(val value: String) {
  Open("Open"),
  Closed("Closed"),
  Processing("Processing"),
  Error("Error")
}
Copy code
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
Copy code
@Serializable
data class EmailModel(
  @Serializable(KUUID::class) override val id: UUID,
  val active: Boolean,
  val address: String,
  @Serializable(KUUID::class) val associateFK: UUID
)
a
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
Copy code
@Serializable
data class Command <T> (
  val status: CommandStatusEnum,
  val messageType: MessageType,
  val message: T
)
r
I will convert the objects to jsonObject,
my question, is, when I have a class, with more than one attribute, how does that line
Copy code
override fun deserialize(decoder: Decoder) = Box(dataSerializer.deserialize(decoder))
Copy code
override fun deserialize(decoder: Decoder) = Command((string, enum,  dataSerializer.deserialize(decoder))
1688 Views