|
| 1 | +/* |
| 2 | + * Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.serialization |
| 6 | + |
| 7 | + |
| 8 | +import kotlinx.serialization.json.* |
| 9 | +import kotlinx.serialization.modules.SerializersModule |
| 10 | +import kotlinx.serialization.modules.polymorphic |
| 11 | +import kotlinx.serialization.test.* |
| 12 | +import kotlin.test.* |
| 13 | + |
| 14 | +class JsonElementPolymorphicErrorTest : JsonTestBase() { |
| 15 | + |
| 16 | + @Serializable |
| 17 | + abstract class Abstract |
| 18 | + |
| 19 | + @Serializable |
| 20 | + data class IntChild(val value: Int) : Abstract() |
| 21 | + |
| 22 | + @Serializable |
| 23 | + data class CollectionChild(val value: Int) : Abstract() |
| 24 | + |
| 25 | + @Serializable |
| 26 | + data class Holder(val value: Abstract) |
| 27 | + |
| 28 | + private val format = Json { |
| 29 | + prettyPrint = false |
| 30 | + serializersModule = SerializersModule { |
| 31 | + polymorphic(Abstract::class) { |
| 32 | + subclass(IntChild::class, IntChildSerializer) |
| 33 | + subclass(CollectionChild::class, CollectionChildSerializer) |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + object IntChildSerializer : JsonTransformingSerializer<IntChild>(serializer()) { |
| 39 | + override fun transformSerialize(element: JsonElement): JsonElement { |
| 40 | + return element.jsonObject.getValue("value") |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + object CollectionChildSerializer : JsonTransformingSerializer<CollectionChild>(serializer()) { |
| 45 | + override fun transformSerialize(element: JsonElement): JsonElement { |
| 46 | + val value = element.jsonObject.getValue("value") |
| 47 | + return JsonArray(listOf(value)) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + fun test() = parametrizedTest { mode -> |
| 53 | + assertFailsWithMessage<SerializationException>("Class with serial name kotlinx.serialization.JsonElementPolymorphicErrorTest.IntChild cannot be serialized polymorphically because it is represented as JsonLiteral. Make sure that its JsonTransformingSerializer returns JsonObject, so class discriminator can be added to it") { |
| 54 | + format.encodeToString( |
| 55 | + Holder.serializer(), |
| 56 | + Holder(IntChild(42)), |
| 57 | + mode |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + assertFailsWithMessage<SerializationException>("Class with serial name kotlinx.serialization.JsonElementPolymorphicErrorTest.CollectionChild cannot be serialized polymorphically because it is represented as JsonArray. Make sure that its JsonTransformingSerializer returns JsonObject, so class discriminator can be added to it") { |
| 62 | + format.encodeToString( |
| 63 | + Holder.serializer(), |
| 64 | + Holder(CollectionChild(42)), |
| 65 | + mode |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments