commonTest.kotlinx.serialization.GenericSerializersOnFileTest.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlinx-serialization-json
Show all versions of kotlinx-serialization-json
Kotlin multiplatform serialization runtime library
/*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:UseSerializers(GenericSerializersOnFileTest.MySerializer::class)
package 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.Json
import kotlin.test.Test
import kotlin.test.assertEquals
class GenericSerializersOnFileTest {
data class GenericClass(val t: T)
@Serializable
data class Holder(val notnull: GenericClass, val nullable: GenericClass?)
class MySerializer(val tSer: KSerializer) : KSerializer> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("my int descriptor", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: GenericClass) {
encoder.encodeString(value.t as String)
}
@Suppress("UNCHECKED_CAST")
override fun deserialize(decoder: Decoder): GenericClass {
return GenericClass(decoder.decodeString() as E)
}
}
@Test
fun testSerialize() {
assertEquals(
"""{"notnull":"Not Null","nullable":null}""",
Json.encodeToString(Holder(notnull = GenericClass("Not Null"), nullable = null))
)
assertEquals(
"""{"notnull":"Not Null","nullable":"Nullable"}""",
Json.encodeToString(Holder(notnull = GenericClass("Not Null"), nullable = GenericClass("Nullable")))
)
}
@Test
fun testDeserialize() {
assertEquals(
Holder(notnull = GenericClass("Not Null"), nullable = null),
Json.decodeFromString("""{"notnull":"Not Null","nullable":null}""")
)
assertEquals(
Holder(notnull = GenericClass("Not Null"), nullable = GenericClass("Nullable")),
Json.decodeFromString("""{"notnull":"Not Null","nullable":"Nullable"}""")
)
}
}