• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.serialization.json
6 
7 import kotlinx.serialization.*
8 import kotlin.test.*
9 
10 class DecodeFromJsonElementTest {
11     @Serializable
12     data class A(val a: Int)
13 
14     @Serializable
15     data class B(val a: A?)
16 
17     @Test
testDecodeTopLevelNullablenull18     fun testDecodeTopLevelNullable() {
19         val a = A(42)
20         val jsonElement = Json.encodeToJsonElement(a)
21         assertEquals(a, Json.decodeFromJsonElement<A?>(jsonElement))
22     }
23 
24     @Test
topLevelNullnull25     fun topLevelNull() {
26         assertNull(Json.decodeFromJsonElement<A?>(JsonNull))
27     }
28 
29     @Test
testInnerNullablenull30     fun testInnerNullable() {
31         val b = B(A(42))
32         val json = Json.encodeToJsonElement(b)
33         assertEquals(b, Json.decodeFromJsonElement(json))
34     }
35 
36     @Test
testInnerNullableNullnull37     fun testInnerNullableNull() {
38         val b = B(null)
39         val json = Json.encodeToJsonElement(b)
40         assertEquals(b, Json.decodeFromJsonElement(json))
41     }
42 
43     @Test
testPrimitivenull44     fun testPrimitive() {
45         assertEquals(42, Json.decodeFromJsonElement(JsonPrimitive(42)))
46         assertEquals(42, Json.decodeFromJsonElement<Int?>(JsonPrimitive(42)))
47         assertEquals(null, Json.decodeFromJsonElement<Int?>(JsonNull))
48     }
49 
50     @Test
testNullableListnull51     fun testNullableList() {
52         assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int>?>(JsonArray(listOf(JsonPrimitive(42)))))
53         assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int?>?>(JsonArray(listOf(JsonPrimitive(42)))))
54         assertEquals(listOf(42), Json.decodeFromJsonElement<List<Int?>>(JsonArray(listOf(JsonPrimitive(42)))))
55         // Nulls
56         assertEquals(null, Json.decodeFromJsonElement<List<Int>?>(JsonNull))
57         assertEquals(null, Json.decodeFromJsonElement<List<Int?>?>(JsonNull))
58     }
59 }
60