-
Notifications
You must be signed in to change notification settings - Fork 653
Description
What is your use-case and why do you need this feature?
I need to serialize using kotlinx.serialization a third party interface IApiError
returned by a Spring controller advice :
@RestControllerAdvice
class SpringAdvice(private val type: SerializerType) {
@ExceptionHandler(CustomException::class)
fun handle(exception: CustomException): ResponseEntity<IApiError> {
return ResponseEntity(IApiError.of(type, exception), 400) // will return an implementation of IApiError either serializable with Jackson or Kotlinx.serialization (annotated
}
}
Spring will execute later the following code that will fail because SerializersKt.serializer(type)
will return a Polymorphic serializer and when the serializer is polymorphic Spring fails
//class KotlinSerializationJsonEncoder
//type being `IApiError` type
//value being `KApiError` a Kotlin annotation with `@Serializable`
Json.Default.encodeToString(SerializersKt.serializer(type), value)
Describe the solution you'd like
I would like to have a way to instruct Kotlinx.serialization that everytime the interface IApiError
needs to be serialized it should use a specific serializer, in this case the KApiError
class serializer.
For example, with Jackson it is possible to do the following :
SimpleAbstractTypeResolver().addMapping(IApiError::class.java, DefaultApiError::class.java)
I've tried declaring the serializer as polymorphic but Spring does not support Open polyphormism.
serializersModule = SerializersModule {
polymorphicDefaultSerializer(IApiError::class) {
KApiError.serializer() as SerializationStrategy<IApiError>
}
}
Also I've tried declaring a custom serializer:
@Serializer(forClass = IApiError::class)
object IApiErrorSerializer: KSerializer<IApiError> { /// }
Thanks for your help 🙏