summaryrefslogtreecommitdiff
path: root/formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt
diff options
context:
space:
mode:
Diffstat (limited to 'formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt')
-rw-r--r--formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt59
1 files changed, 59 insertions, 0 deletions
diff --git a/formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt b/formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt
new file mode 100644
index 00000000..5db3d773
--- /dev/null
+++ b/formats/json-tests/commonTest/src/kotlinx/serialization/json/DecodeFromJsonElementTest.kt
@@ -0,0 +1,59 @@
+/*
+ * 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<A?>(jsonElement))
+ }
+
+ @Test
+ fun topLevelNull() {
+ assertNull(Json.decodeFromJsonElement<A?>(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<Int?>(JsonPrimitive(42)))
+ assertEquals(null, Json.decodeFromJsonElement<Int?>(JsonNull))
+ }
+
+ @Test
+ fun testNullableList() {
+ assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int>?>(JsonArray(listOf(JsonPrimitive(42)))))
+ assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int?>?>(JsonArray(listOf(JsonPrimitive(42)))))
+ assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int?>>(JsonArray(listOf(JsonPrimitive(42)))))
+ // Nulls
+ assertEquals(null, Json.decodeFromJsonElement<List<Int>?>(JsonNull))
+ assertEquals(null, Json.decodeFromJsonElement<List<Int?>?>(JsonNull))
+ }
+}