All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.stormbit.vksdk.objects.models.Response.kt Maven / Gradle / Ivy

The newest version!
package com.github.stormbit.vksdk.objects.models

import com.github.stormbit.vksdk.utils.getString
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject

@Serializable(with = Response.Companion::class)
sealed class Response {

    @Serializable
    data class Success(val response: JsonElement) : Response()

    @Serializable
    data class Error(
        val error: String
    ) : Response()

    companion object : KSerializer {
        override fun deserialize(decoder: Decoder): Response {
            val json = decoder.decodeSerializableValue(JsonObject.serializer())

            return if (json.containsKey("response")) {
                Success(json["response"]!!)
            } else {
                Error(json["error"].toString())
            }
        }

        override fun serialize(encoder: Encoder, value: Response) {
            encoder.encodeSerializableValue(serializer(), value)
        }

        override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("response", PrimitiveKind.STRING)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy