10

Not sure if it is possible yet but for the life of me I cannot figure out how to serialize this.

sealed class ServiceResult<out T : Any> {
    data class Success<out T : Any>(val data: T) : ServiceResult<T>()
    data class Error(val exception: Exception) : ServiceResult<Nothing>()
}

Everything that is stuff into T is using @Serializable ex:

@Serializable
data class GalleryDTO(
    override val id: Int,
    override val dateCreated: Long,
    override val dateUpdated: Long,
    val name:String,
    val description:String,
    val photos:List<DTOMin>
) : DTO 
4

2 Answers 2

4

As Animesh Sahu already mentioned there is an issue for this topic that is still open, but the solution using a surrogate suggested by Михаил Нафталь for serialization of Error can actually be used also to serialize the polymorphic ServiceResult, by creating a surrogate that mixes the fields of Success and Error. For the sake of simplicity in the example I only represent the exception message.

@Serializable(with = ServiceResultSerializer::class)
sealed class ServiceResult<out T : Any> {
    data class Success<out T : Any>(val data: T) : ServiceResult<T>()
    data class Error(val exceptionMessage: String?) : ServiceResult<Nothing>()
}

class ServiceResultSerializer<T : Any>(
    tSerializer: KSerializer<T>
) : KSerializer<ServiceResult<T>> {
    @Serializable
    @SerialName("ServiceResult")
    data class ServiceResultSurrogate<T : Any>(
        val type: Type,
        // The annotation is not necessary, but it avoids serializing "data = null" 
        // for "Error" results.
        @EncodeDefault(EncodeDefault.Mode.NEVER)
        val data: T? = null,
        @EncodeDefault(EncodeDefault.Mode.NEVER)
        val exceptionMessage: String? = null
    ) {
        enum class Type { SUCCESS, ERROR }
    }

    private val surrogateSerializer = ServiceResultSurrogate.serializer(tSerializer)

    override val descriptor: SerialDescriptor = surrogateSerializer.descriptor

    override fun deserialize(decoder: Decoder): ServiceResult<T> {
        val surrogate = surrogateSerializer.deserialize(decoder)
        return when (surrogate.type) {
            ServiceResultSurrogate.Type.SUCCESS ->
                if (surrogate.data != null)
                    ServiceResult.Success(surrogate.data)
                else
                    throw SerializationException("Missing data for successful result")
            ServiceResultSurrogate.Type.ERROR ->
                ServiceResult.Error(surrogate.exceptionMessage)
        }
    }

    override fun serialize(encoder: Encoder, value: ServiceResult<T>) {
        val surrogate = when (value) {
            is ServiceResult.Error -> ServiceResultSurrogate(
                ServiceResultSurrogate.Type.ERROR,
                exceptionMessage = value.exceptionMessage
            )
            is ServiceResult.Success -> ServiceResultSurrogate(
                ServiceResultSurrogate.Type.SUCCESS,
                data = value.data
            )
        }
        surrogateSerializer.serialize(encoder, surrogate)
    }
}

This solution can also be easily extended to support nullable Ts. In this case when deserializing you will also have to check if null is a valid value for T (it can be done by checking descriptor.isNullable on tSerializer) and you will also have to cast data as T.

0

Polymorphic serialization will be a mess in this case (you will have to manually register all possible types passed as a generic parameter to ServiceResult<T>), and will have several limitations (it would be impossible to register primitive types (including Nothing and String) as generic parameters, for instance). If you only need serialization (aka encoding), I'd recommend to serialize both subtypes independently (for convenience, wrap subtype determination into auxilary function):

inline fun <reified T : Any> serializeServiceResult(x: ServiceResult<T>) = when (x) {
    is ServiceResult.Success -> Json.encodeToString(x)
    is ServiceResult.Error -> Json.encodeToString(x)
}

To serialize ServiceResult.Success you need just to mark it with @Serializable annotation. The tricky part here is serialization of ServiceResult.Error, or more precisely, serialization of its exception: Exception field. I'd suggest to serialize only its message (via surrogate):

sealed class ServiceResult<out T : Any> {
    @Serializable
    data class Success<out T : Any>(val data: T) : ServiceResult<T>()

    @Serializable(with = ErrorSerializer::class)
    data class Error(val exception: Exception) : ServiceResult<Nothing>()
}

@Serializable
private data class ErrorSurrogate(val error: String)

class ErrorSerializer : KSerializer<ServiceResult.Error> {
    override val descriptor: SerialDescriptor = ErrorSurrogate.serializer().descriptor

    override fun deserialize(decoder: Decoder): ServiceResult.Error {
        val surrogate = decoder.decodeSerializableValue(ErrorSurrogate.serializer())
        return ServiceResult.Error(Exception(surrogate.error))
    }

    override fun serialize(encoder: Encoder, value: ServiceResult.Error) {
        val surrogate = ErrorSurrogate(value.exception.toString())
        encoder.encodeSerializableValue(ErrorSurrogate.serializer(), surrogate)
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.