blob: 5db3d773100d5768e319daa55ee33810443caab4 (
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
55
56
57
58
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))
}
}
|