So I have this class to for Json deserialization:
@Serializable
data class NetworkUser(
@SerialName("id")
val id: Long,
...
@Serializable(RoleSerializer::class)
@SerialName("role")
val role: List<Role>
)
Serializer for Role
Enum class:
object RoleSerializer : KSerializer<Role> {
override fun deserialize(decoder: Decoder): Role =
Role.valueOf(decoder.decodeString())
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(
serialName = "Instant",
kind = PrimitiveKind.STRING,
)
override fun serialize(encoder: Encoder, value: Role) =
encoder.encodeString(value.name)
}
But I get this error
How can I use it with List<Role>
instead of just Role
? I don't really want to create another KSerializer
just for parsing a list, it is boilerplate code
In my case I need it for Android Retrofit Json parsing, if I need to create two KSerializer
for object and list of objects then I better return back Gson
serialization and TypeAdapters
, you only create a Type Adapter for object once with Gson, no need to create it for lists, also you don't need to add annotation to every field where it's used
Maybe try:
@SerialName("role") val role: List<@Serializable(with = RoleSerializer::class) Role>