commonTest.kotlinx.serialization.json.JsonElementDecodingTest.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
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)
}
}