commonTest.kotlinx.serialization.json.DecodeFromJsonElementTest.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-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlin.test.*
class DecodeFromJsonElementTest {
@Serializable
data class A(val a: Int)
@Serializable
data class B(val a: A?)
@Test
fun testDecodeTopLevelNullable() {
val a = A(42)
val jsonElement = Json.encodeToJsonElement(a)
assertEquals(a, Json.decodeFromJsonElement(jsonElement))
}
@Test
fun topLevelNull() {
assertNull(Json.decodeFromJsonElement(JsonNull))
}
@Test
fun testInnerNullable() {
val b = B(A(42))
val json = Json.encodeToJsonElement(b)
assertEquals(b, Json.decodeFromJsonElement(json))
}
@Test
fun testInnerNullableNull() {
val b = B(null)
val json = Json.encodeToJsonElement(b)
assertEquals(b, Json.decodeFromJsonElement(json))
}
@Test
fun testPrimitive() {
assertEquals(42, Json.decodeFromJsonElement(JsonPrimitive(42)))
assertEquals(42, Json.decodeFromJsonElement(JsonPrimitive(42)))
assertEquals(null, Json.decodeFromJsonElement(JsonNull))
}
@Test
fun testNullableList() {
assertEquals(listOf(42), Json.decodeFromJsonElement?>(JsonArray(listOf(JsonPrimitive(42)))))
assertEquals(listOf(42), Json.decodeFromJsonElement?>(JsonArray(listOf(JsonPrimitive(42)))))
assertEquals(listOf(42), Json.decodeFromJsonElement>(JsonArray(listOf(JsonPrimitive(42)))))
// Nulls
assertEquals(null, Json.decodeFromJsonElement?>(JsonNull))
assertEquals(null, Json.decodeFromJsonElement?>(JsonNull))
}
}