kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Can't access default serializer which is crutial for polymorphism.

Open krottv opened this issue 4 years ago • 2 comments

Describe the bug

Currently if we provide @Serializable(with = CustomSerializer) annotation then we no longer have access to original generated serializer. Which is fine in most cases, but it is critical when we deal with polymotphism. The main issue is that we run into dependency cycle.

To Reproduce The following code crashes the app with NPE

@Serializable(with = MediaImageSerializer::class)
@SerialName("image")
data class MediaImage(...)

object MediaImageSerializer : JsonTransformingSerializer<MediaImage>(MediaImage.serializer()) 

The problem here is that we can't avoid @Serializable(with = MediaImageSerializer::class) here. Because the object that contains mediaImage doesn't know its type:

@Serializable
class Template(medias: List<@Serializable with [we don't know which serializer to use] Media>)

Expected behavior

We need to be able to use original generated serializer

Environment

  • Kotlin version: 1.4.30-RC
  • Library version: 1.0.1
  • Kotlin platforms: JVM

krottv avatar Jan 27 '21 12:01 krottv

Duplicate of #1169, looks like

As a workaround, you can use @file:UseSerializers instead of repeating @Serializable(MediaImageSerializer::class)

sandwwraith avatar Jan 29 '21 14:01 sandwwraith

@sandwwraith where should I put @file:UseSerializers? I tried it everywhere, doesn't make any difference, still the dafault one is always used. It doesn't work for polymorphism, seems like another issue

krottv avatar Feb 02 '21 09:02 krottv

Fixed by #1169

sandwwraith avatar Jul 10 '24 14:07 sandwwraith