summaryrefslogtreecommitdiff
path: root/formats/json/commonTest/src/kotlinx/serialization/json/JsonElementDecodingTest.kt
blob: d0b105a091d945b6ba8a979d0e607fb6f5e47648 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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?>(A(), """{}""")
        assertSerializedForm<A?>(null, "null")
    }

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

    @Test
    fun testTopLevelNullablePrimitive() {
        assertSerializedForm<Int?>(42, """42""")
        assertSerializedForm<Int?>(null, """null""")
    }

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

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

    private inline fun <reified T> 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)
    }
}