-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tagged3.kt
105 lines (88 loc) · 2.67 KB
/
Tagged3.kt
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package net.sarazan.martok
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonContentPolymorphicSerializer
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
@Serializable(with = Empty.UnionSerializer::class)
sealed class Empty {
abstract val type: Type
@Serializable
enum class Type(
val serialName: String
) {
@SerialName("foo") FOO("foo"),
@SerialName("bar") BAR("bar");
}
@Serializable
class EmptyFoo : Empty() {
override val type: Type = Type.FOO
}
@Serializable
class EmptyBar : Empty() {
override val type: Type = Type.BAR
}
object UnionSerializer : JsonContentPolymorphicSerializer<Empty>(Empty::class) {
override fun selectDeserializer(element: JsonElement) = when(
val type = element.jsonObject["type"]
) {
JsonPrimitive(Type.FOO.serialName) -> EmptyFoo.serializer()
JsonPrimitive(Type.BAR.serialName) -> EmptyBar.serializer()
else -> throw IllegalArgumentException("Unexpected type: $type")
}
}
}
@Serializable
data class NestedLiteralUnion(
val id: String,
val data: Data
) {
@Serializable(with = Data.UnionSerializer::class)
sealed class Data {
abstract val some_type: SomeType
@Serializable
enum class SomeType(
val serialName: String
) {
@SerialName("foo") FOO("foo"),
@SerialName("bar") BAR("bar");
}
@Serializable
data class DataFoo(
val data: Foo
) : Data() {
override val some_type: SomeType = SomeType.FOO
}
@Serializable
data class DataBar(
val data: Bar
) : Data() {
override val some_type: SomeType = SomeType.BAR
}
object UnionSerializer : JsonContentPolymorphicSerializer<Data>(Data::class) {
override fun selectDeserializer(element: JsonElement) = when(
val type = element.jsonObject["some_type"]
) {
JsonPrimitive(SomeType.FOO.serialName) -> DataFoo.serializer()
JsonPrimitive(SomeType.BAR.serialName) -> DataBar.serializer()
else -> throw IllegalArgumentException("Unexpected type: $type")
}
}
}
}
@Serializable
data class Foo(
val foo: String
)
@Serializable
data class Bar(
val bar: String
)