Hey, I'm trying to serialize some polymorphic JSON...
# serialization
n
Hey, I'm trying to serialize some polymorphic JSON using serialization, and I get everything to work when the polymorphic objects are contained in an array or wrapped in another object, but when the polymorphic object is at top-level, it won't work and I won't get any "type"-key. The docs say that I can use PolymorphicSerializer to stringify, and using that gives me the "type"-key, but I'm unsure how to use that since i'm using Ktor and I want to avoid the boilerplate of doing this at every call.respond(..). Has anyone done this and might give me some pointers? :)
c
Using sealed classes is the easiest, as it supports polymorphic serialization out-of-the-box. I think adding
@Polymorphic
to the base type/interface will enable similar behavior as well, allowing you to use that base class’s serializer with the sub-types registered in a serializers module
Copy code
@Serializable
@Polymorphic <-- this is the key
abstract class BaseResponse

@Serializable
class Response1 : BaseResponse()

@Serializable
class Response2 : BaseResponse()

val polymorphicJson = Json(
    configuration = JsonConfiguration(
        
    ),
    context = SerializersModule {
        polymorphic(BaseResponse::class) {
            Response1::class with Response1.serializer() // 3
            Response2::class with Response2.serializer() // 4
        }
    }
)
val parsed = polymorphicJson.parse(BaseResponse.serializer(), "...")
👍 1
n
Thanks! But I now suspect my problem has more with Ktor to do than kotlinx.serialization. I solved it by using a custom ContentConverter