Is it possible to add values to a KSerializer? I w...
# serialization
t
Is it possible to add values to a KSerializer? I want to add
error
to an API response I send out so I thought in the serializer to just add the
error
field and the only way I got it working was to just make a Surrogate of my error, was wondering if there was a better solution to this than that.
a
do you have an example? What will the value of
error
be? If you’re using JSON you could try a custom
JsonTransformingSerializer
, but I suspect that being explicit and creating a new
@Serializable class
with a specific field is more clear and understandable
t
Ah sorry for the late response,
error
will always be true which is why I would prefer to not make another class
Copy code
internal object RouteErrorSerializer : KSerializer<RouteError> {
    @Serializable
    data class Surrogate(
        val error: Boolean,
        @SerialName("status_code")
        val statusCode: Int,
        val message: String?
    )

    private val surrogateSerializer = Surrogate.serializer()
    override val descriptor = surrogateSerializer.descriptor

    override fun deserialize(decoder: Decoder): RouteError {
        val surrogate = surrogateSerializer.deserialize(decoder)

        return RouteError(
            surrogate.statusCode,
            surrogate.message
        )
    }

    override fun serialize(encoder: Encoder, value: RouteError) {
        surrogateSerializer.serialize(encoder, Surrogate(
            true,
            value.statusCode,
            value.message
        ))
    }
}
I'm sending responses via ktor so I just wanted to apply
error
onto the JSON object so in the future I can wrap responses in Kotlin's
Result
a
is RouteError a class that you control? You could just add a
@EncodeDefault val error: Boolean = true
into the body (not constructor), and maybe annotate it with
@Deprecated
with the level set to ‘hidden’
t
Interesting, I didn't even know that was an annotation I'll try it out
yep seems to be working fine, thanks so much
a
my pleasure!