Hey, I need a little help with generics. I've trie...
# serialization
g
Hey, I need a little help with generics. I've tried searching for a solution but I couldn't find any. I want to encode to / decode from JSON. I have the following class:
Copy code
data class Nice<T: @Serializable Any>(
    @SerialName("id") val id: String,
    @SerialName("type") val type: String,
    // ... about 5 more parameters ...
    @SerialName("value") val value: T,
)
Based on the
type
parameter, the value could be a couple of serializable things: list of a data class(id,name) items, a single data class(id,name) item, or a boolean value. • If I don't set a custom serializer with
@Serializable(with = ...)
, the encoding to JSON works, but decoding from JSON runs into
Star projections in type arguments are not allowed, but had null
error (trying to decode it as
Nice<*>
. • If I set a custom serializer by implementing
JsonContentPolymorphicSerializer
I get
Class 'Nice' is not registered for polymorphic serialization in the scope of 'Nice'.
even for encoding. Is there any way to tell the deserializer that if the
type
value is something, decode
value
as either a list / single item / boolean without implementing a full on KSerializer? There are quite a few parameters in the class and would be nice not writing encode / decode statements for each one of them.
g
Well, the thing is that in this example the
Interaction<T>
would be also in another class that would be encoded / decoded. If I specify
@Serializable(with = InteractionJsonSerializer::class)
on the Interaction class, even encoding the Interaction results in
Class 'Interaction' is not registered for polymorphic serialization in the scope of 'Interaction'.
error
So add this to the equation:
Copy code
@Serializable
data class InteractionParent(
    val interaction: List<Interaction<*>>
)
e