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

commonTest.kotlinx.serialization.GenericSerializersOnFileTest.kt Maven / Gradle / Ivy

There is a newer version: 1.7.3
Show newest version
/*
 * 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"}""")
        )
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy