-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tagged4.kt
82 lines (71 loc) · 2.24 KB
/
Tagged4.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
/****************************************************
** DO NOT EDIT THIS FILE BY HAND! **
** This file was automatically generated by Martok **
** More info at https://github.com/asarazan/martok **
*****************************************************/
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 = Thing.UnionSerializer::class)
sealed class Thing {
abstract val state: State
abstract val type: Type
@Serializable
enum class Type(
val serialName: String
) {
@SerialName("foo") FOO("foo"),
@SerialName("bar") BAR("bar");
}
@Serializable
enum class State(
val serialName: String
) {
@SerialName("first") FIRST("first"),
@SerialName("second") SECOND("second");
}
@Serializable
data class ThingFoo(
override val state: State
) : Thing() {
override val type: Type = Type.FOO
}
@Serializable
data class ThingBar(
override val state: State
) : Thing() {
override val type: Type = Type.BAR
}
object UnionSerializer : JsonContentPolymorphicSerializer<Thing>(Thing::class) {
override fun selectDeserializer(element: JsonElement) = when(
val type = element.jsonObject["type"]
) {
JsonPrimitive(Type.FOO.serialName) -> ThingFoo.serializer()
JsonPrimitive(Type.BAR.serialName) -> ThingBar.serializer()
else -> throw IllegalArgumentException("Unexpected type: $type")
}
}
}
@Serializable
data class Base(
val state: State
) {
@Serializable
enum class State(
val serialName: String
) {
@SerialName("first") FIRST("first"),
@SerialName("second") SECOND("second");
}
}