All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonTest.kotlinx.serialization.json.DecodeFromJsonElementTest.kt Maven / Gradle / Ivy

There is a newer version: 1.7.3
Show newest version
/*
 * 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))
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy