Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KTOR-3782 Fix contextual serializer with kotlinx #2865

Merged
merged 1 commit into from
Mar 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ internal fun serializerFromTypeInfo(
typeInfo: TypeInfo,
module: SerializersModule
): KSerializer<*> {
return module.getContextual(typeInfo.type)
?: typeInfo.kotlinType?.let { module.serializerOrNull(it) }
return typeInfo.kotlinType
?.let { type ->
if (type.arguments.isEmpty()) null // fallback to simple case because of
// https://github.com/Kotlin/kotlinx.serialization/issues/1870
else module.serializerOrNull(type)
}
?: module.getContextual(typeInfo.type)
?: typeInfo.type.serializer()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,16 @@ import io.ktor.serialization.kotlinx.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.serialization.kotlinx.test.*
import io.ktor.test.dispatcher.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.reflect.*
import kotlin.test.*

@OptIn(ExperimentalSerializationApi::class)
Expand Down Expand Up @@ -54,4 +62,91 @@ class JsonSerializationTest : AbstractSerializationTest<Json>() {
assertEquals("""{"a":"1","b":["c",2]}""", result.decodeToString())
}
}

@Test
fun testContextual() = testSuspend {
val serializer = KotlinxSerializationConverter(
Json {
prettyPrint = true
encodeDefaults = true
serializersModule =
SerializersModule {
contextual(Either::class) { serializers: List<KSerializer<*>> ->
EitherSerializer(serializers[0], serializers[1])
}
}
}
)
val dogJson = """{"age": 8,"name":"Auri"}"""
assertEquals(
Either.Right(DogDTO(8, "Auri")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(dogJson.toByteArray())
)
)
val errorJson = """{"message": "Some error"}"""
assertEquals(
Either.Left(ErrorDTO("Some error")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(errorJson.toByteArray())
)
)

val emptyErrorJson = "{}"
assertEquals(
Either.Left(ErrorDTO("Some default error")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(emptyErrorJson.toByteArray())
)
)
}
}

@Serializable
data class DogDTO(val age: Int, val name: String)

@Serializable
data class ErrorDTO(val message: String = "Some default error")

sealed class Either<out L, out R> {

data class Left<out L>(val left: L) : Either<L, Nothing>()

data class Right<out R>(val right: R) : Either<Nothing, R>()
}

class EitherSerializer<L, R>(
private val leftSerializer: KSerializer<L>,
private val rightSerializer: KSerializer<R>,
) : KSerializer<Either<L, R>> {

override val descriptor: SerialDescriptor =
buildClassSerialDescriptor("NetworkEitherSerializer") {
element("left", leftSerializer.descriptor)
element("right", rightSerializer.descriptor)
}

override fun deserialize(decoder: Decoder): Either<L, R> {
require(decoder is JsonDecoder) { "only works in JSON format" }
val element: JsonElement = decoder.decodeJsonElement()

return try {
Either.Right(decoder.json.decodeFromJsonElement(rightSerializer, element))
} catch (throwable: Throwable) {
Either.Left(decoder.json.decodeFromJsonElement(leftSerializer, element))
}
}

override fun serialize(encoder: Encoder, value: Either<L, R>) {
when (value) {
is Either.Left -> encoder.encodeSerializableValue(leftSerializer, value.left)
is Either.Right -> encoder.encodeSerializableValue(rightSerializer, value.right)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

package io.ktor.util.debug

import java.lang.ClassNotFoundException
import java.lang.management.*

internal actual object IntellijIdeaDebugDetector {
Expand Down