Created
October 22, 2024 11:13
-
-
Save mutkuensert/2a8fb32fecdd61d164058fbe307a6743 to your computer and use it in GitHub Desktop.
SerialDescriptor example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.serialization.ExperimentalSerializationApi | |
import kotlinx.serialization.KSerializer | |
import kotlinx.serialization.builtins.serializer | |
import kotlinx.serialization.descriptors.SerialDescriptor | |
import kotlinx.serialization.descriptors.buildClassSerialDescriptor | |
import kotlinx.serialization.descriptors.element | |
import kotlinx.serialization.encoding.CompositeDecoder | |
import kotlinx.serialization.encoding.Decoder | |
import kotlinx.serialization.encoding.Encoder | |
import kotlinx.serialization.encoding.decodeStructure | |
object ErrorModelSerializer : KSerializer<ErrorModel> { | |
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("error") { | |
element<String>("message", isOptional = true) | |
element<Int>("errorCode", isOptional = true) | |
element<String>("type", isOptional = true) | |
} | |
@OptIn(ExperimentalSerializationApi::class) | |
override fun deserialize(decoder: Decoder): ErrorModel { | |
return decoder.decodeStructure(descriptor) { | |
var errorMessage: String? = null | |
var errorCode: String? = null | |
var errorType: String? = null | |
while (true) { | |
when (decodeElementIndex(descriptor)) { | |
0 -> errorMessage = | |
decodeNullableSerializableElement(descriptor, 0, String.serializer(), null) | |
1 -> errorCode = | |
decodeNullableSerializableElement(descriptor, 1, String.serializer(), null) | |
2 -> errorType = | |
decodeNullableSerializableElement(descriptor, 2, String.serializer(), null) | |
CompositeDecoder.DECODE_DONE -> break | |
} | |
} | |
return@decodeStructure when { | |
errorCode == "warning_token_expire" -> { | |
ErrorModel( | |
ErrorModel.GenericErrorType.TOKEN_EXPIRED, | |
"Token Expired" | |
) | |
} | |
errorMessage == "" -> { | |
ErrorModel(ErrorModel.GenericErrorType.PARSE_ERROR) | |
} | |
errorType == "VALIDATION" -> { | |
ErrorModel( | |
errorCode, | |
errorMessage, | |
ErrorModel.ErrorType.VALIDATION | |
) | |
} | |
else -> { | |
ErrorModel( | |
errorCode, | |
errorMessage, | |
ErrorModel.ErrorType.UNKNOWN | |
) | |
} | |
} | |
} | |
} | |
override fun serialize(encoder: Encoder, value: ErrorModel) { | |
//Because this is a response, we only need to deserialize | |
encoder.encodeString("") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment