blob: aa543d6793ed195e07ea247d0f97b8e0ddcba03b (
plain)
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
|
package moe.nea.firmament.util.json
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
class SingletonSerializableList<T>(val child: KSerializer<T>) : KSerializer<List<T>> {
override val descriptor: SerialDescriptor
get() = JsonElement.serializer().descriptor
override fun deserialize(decoder: Decoder): List<T> {
decoder as JsonDecoder
val list = JsonElement.serializer().deserialize(decoder)
if (list is JsonArray) {
return list.map {
decoder.json.decodeFromJsonElement(child, it)
}
}
return listOf(decoder.json.decodeFromJsonElement(child, list))
}
override fun serialize(encoder: Encoder, value: List<T>) {
ListSerializer(child).serialize(encoder, value)
}
}
|