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

commonTest.kotlinx.serialization.json.JsonElementDecodingTest.kt Maven / Gradle / Ivy

There is a newer version: 1.7.3
Show newest version
package kotlinx.serialization.json

import kotlinx.serialization.Serializable
import kotlin.test.*

class JsonElementDecodingTest : JsonTestBase() {

    @Serializable
    data class A(val a: Int = 42)

    @Test
    fun testTopLevelClass() = assertSerializedForm(A(), """{}""".trimMargin())

    @Test
    fun testTopLevelNullableClass() {
        assertSerializedForm(A(), """{}""")
        assertSerializedForm(null, "null")
    }

    @Test
    fun testTopLevelPrimitive() = assertSerializedForm(42, """42""")

    @Test
    fun testTopLevelNullablePrimitive() {
        assertSerializedForm(42, """42""")
        assertSerializedForm(null, """null""")
    }

    @Test
    fun testTopLevelList() = assertSerializedForm(listOf(42), """[42]""")

    @Test
    fun testTopLevelNullableList() {
        assertSerializedForm?>(listOf(42), """[42]""")
        assertSerializedForm?>(null, """null""")
    }

    private inline fun  assertSerializedForm(value: T, expectedString: String) {
        val element = Json.encodeToJsonElement(value)
        assertEquals(expectedString, element.toString())
        assertEquals(value, Json.decodeFromJsonElement(element))
    }

    @Test
    fun testDeepRecursion() {
        // Reported as https://github.com/Kotlin/kotlinx.serialization/issues/1594
        var json = """{ "a": %}"""
        for (i in 0..12) {
            json = json.replace("%", json)
        }
        json = json.replace("%", "0")
        Json.parseToJsonElement(json)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy