Skip to content

Commit

Permalink
add tests to show nullable Json{Element,Primitive,Null} decoding works
Browse files Browse the repository at this point in the history
  • Loading branch information
pschichtel committed Sep 29, 2023
1 parent 99e3f91 commit b709c0d
Showing 1 changed file with 57 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package kotlinx.serialization.json

import kotlinx.serialization.Serializable
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlin.test.*

class JsonElementDecodingTest : JsonTestBase() {
Expand Down Expand Up @@ -51,4 +53,58 @@ class JsonElementDecodingTest : JsonTestBase() {
json = json.replace("%", "0")
Json.parseToJsonElement(json)
}

private open class NullableSerializer<T : Any>(private val serializer: KSerializer<T>) : KSerializer<T?> {
final override val descriptor: SerialDescriptor = serializer.descriptor.nullable

final override fun serialize(encoder: Encoder, value: T?) {
if (value == null) {
encoder.encodeNull()
} else {
serializer.serialize(encoder, value)
}
}

final override fun deserialize(decoder: Decoder): T = serializer.deserialize(decoder)
}

private object NullableJsonElementSerializer : NullableSerializer<JsonElement>(JsonElement.serializer())
private object NullableJsonPrimitiveSerializer : NullableSerializer<JsonPrimitive>(JsonPrimitive.serializer())
private object NullableJsonNullSerializer : NullableSerializer<JsonNull>(JsonNull.serializer())

@Test
fun testNullableJsonElementDecoding() {
@Serializable
data class Wrapper(
@Serializable(NullableJsonElementSerializer::class)
val value: JsonElement? = null,
)

assertSerializedForm<Wrapper>(Wrapper(value = JsonNull), """{"value":null}""")
assertSerializedForm<Wrapper>(Wrapper(value = null), """{}""")
}

@Test
fun testNullableJsonPrimitiveDecoding() {
@Serializable
data class Wrapper(
@Serializable(NullableJsonPrimitiveSerializer::class)
val value: JsonPrimitive? = null,
)

assertSerializedForm<Wrapper>(Wrapper(value = JsonNull), """{"value":null}""")
assertSerializedForm<Wrapper>(Wrapper(value = null), """{}""")
}

@Test
fun testNullableJsonNullDecoding() {
@Serializable
data class Wrapper(
@Serializable(NullableJsonNullSerializer::class)
val value: JsonNull? = null,
)

assertSerializedForm<Wrapper>(Wrapper(value = JsonNull), """{"value":null}""")
assertSerializedForm<Wrapper>(Wrapper(value = null), """{}""")
}
}

0 comments on commit b709c0d

Please sign in to comment.