Is there any way to define a serializer for a top-...
# serialization
s
Is there any way to define a serializer for a top-level list as a contextual serializer in a
SerializersModule
?
My options right now seem to be: • wrap the list in a data class and then add that data class's serializer to the module • check if it's a list in my
stringify()
call and use the built in
.list
extension function, but that would require reflection with how I'm doing it
s
you need serializer for
List<@Contextual MyData>
? try
ContextualSerializer(MyData::class).list
s
I have a Serializers Module like this:
Copy code
internal val fooModule = SerializersModule {
    contextual(Foo::class, Foo.serializer())
    contextual(Bar::class, Bar.serializer())
    //etc
}
And I need to serialize a body that is a top-level list when I make a server request. My serialize function searches the serialization context I have defined in my library like so:
Copy code
internal inline fun <reified T : Any> serialize(obj: T) = json.stringify(serializationContext.getContextualOrThrow(), obj)

internal val serializationContext = SerializersModule {
    include(
        fooModule + otherModule + otherModule2 //etc
    )
}
I can create a separate function for serializing a top-level list by adding it's specific
serializer().list
, but I was wondering if there is a way to add it to my SerializersModule using it's list serializer.
Right now I am doing this:
Copy code
@Serializable
data class FooList(
    val foos: List<Foo>
) {
    @Serializer(FooList::class)
    companion object : KSerializer<FooList> {
        override val descriptor: SerialDescriptor = StringDescriptor.withName("FooList")

        override fun serialize(encoder: Encoder, obj: FooList) {
            Foo.serializer().list.serialize(encoder, obj.foos)
        }

        override fun deserialize(decoder: Decoder): FooList {
            return FooList(Foo.serializer().list.deserialize(decoder))
        }
    }
}

@Serializable
data class Foo(
    val name: String,
    val id: Int
)
And then adding both
FooList
and
Foo
serializers to my SerializersModule. It's just a bit tedious for anytime I want to serialize a top-level list.